﻿Imports DotNetNuke
Imports DotNetNuke.Common
Imports DotNetNuke.Security
Imports DotNetNuke.Entities.Profile
Imports DotNetNuke.Entities.Users
Imports DotNetNuke.Entities.Users.UserProfile
Imports System.Web.UI
Imports Telerik.Web.UI
Imports DotNetNuke.Security.Membership
Imports DotNetNuke.Services.Mail
Imports DotNetNuke.Security.Roles
Imports System.Collections.Generic
Imports DotNetNuke.Entities.Modules
Imports DotNetNuke.Services.Localization.Localization

Namespace dnnWerk.Modules.Users

    Partial Class uc_Manage
        Inherits UserModuleBase

#Region "Private Members"

        Private _IsReportResult As Boolean = False
        Private _PageNeedsToPostback As Boolean = False

        'Private ReadOnly Property Userlist(ByVal RoleId As Integer) As ArrayList
        '    Get
        '        Dim _userlist As ArrayList = Nothing
        '        If Not DataCache.GetCache("USERLIST_" & PortalId.ToString & "_" & RoleId.ToString) Is Nothing Then
        '            _userlist = CType(DataCache.GetCache("USERLIST_" & PortalId.ToString & "_" & RoleId.ToString), ArrayList)
        '        End If
        '        Return _userlist
        '    End Get
        'End Property



#End Region

#Region "Event Handlers"

        Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init

            DotNetNuke.Framework.AJAX.RegisterScriptManager()
            DotNetNuke.Framework.AJAX.RegisterPostBackControl(btnUpdateProfile)

            InitializeForm()

            ProcessFormTemplate(plhUser, Template_EditAccount(CurrentLocale), User, _PageNeedsToPostback)
            ProcessFormTemplate(plhProfile, Template_EditProfile(CurrentLocale), User, _PageNeedsToPostback)
            ProcessFormTemplate(plhCreate, Template_CreateAccount(CurrentLocale), Nothing, _PageNeedsToPostback)

            BindUserTabs()
            LoadAdditionalControls()

        End Sub

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            If Not Page.IsPostBack Then

                BindRoles()
                BindSearchColOptions()
                PersonalizeOptions()

                If CanRunReports Then
                    BindReports()
                Else
                    ctlFilterTabs.Tabs(1).Visible = False
                    pvFilters.PageViews(1).Visible = False
                End If

                If Not Request.QueryString("uid") Is Nothing Then
                    BindUser(Convert.ToInt32(Request.QueryString("uid")))
                Else
                    'BindUsers()
                End If

            End If

            pnlHostEval.Visible = False

        End Sub

        Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExport.Click
            Export()
        End Sub

        Protected Sub btnAction_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAction.Click

            Dim strCommand As String = CType(sender, Button).CommandName

            If strCommand.ToLower = "back" Then

                If Not Request.QueryString("uid") Is Nothing AndAlso Not Request.QueryString("RoleId") Then
                    Dim roleid As String = ""
                    If String.IsNullOrEmpty(Request.QueryString("RoleId")) Then
                        roleid = PreSelectRole.ToString
                    Else
                        roleid = Request.QueryString("RoleId")
                    End If
                    Dim url As String = NavigateURL(TabId, "", "RoleId=" & roleid)
                    Response.Redirect(url)
                End If

                pnlCreate.Visible = False
                pnlUser.Visible = False
                pnlGrid.Visible = True

                If AllowCreate Then
                    btnAction.CommandName = "Create"
                    btnAction.Text = GetString("CreateUser", LocalResourceFile)
                    btnAction.Enabled = True
                Else
                    btnAction.Enabled = False
                    btnAction.Text = ""
                    btnAction.CommandName = ""
                End If


            Else

                btnAction.CommandName = "back"
                btnAction.Text = GetString("Back", LocalResourceFile)
                btnAction.Enabled = True

                BindUserCreateForm()

            End If

        End Sub

        Protected Sub btnCreateUser_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCreateUser.Click

            pnlCreateUserError.Visible = False
            pnlCreateUserSuccess.Visible = False

            Dim strMessage As String = ""

            Dim blnUpdateUsername As Boolean = False
            Dim blnUpdateFirstname As Boolean = False
            Dim blnUpdateLastname As Boolean = False
            Dim blnUpdateDisplayname As Boolean = False
            Dim blnUpdatePassword As Boolean = False
            Dim blnUpdateEmail As Boolean = False

            Dim txtUsername As RadTextBox = CType(FindControlRecursive(plhCreate, plhCreate.ID & "_" & Constants.ControlId_Username), RadTextBox)
            blnUpdateUsername = (Not txtUsername Is Nothing)

            If blnUpdateUsername Then
                If Not IsValidUserAttribute(Constants.User_Username, plhCreate) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Username, plhCreate)
                End If
            End If

            Dim txtEmail As RadTextBox = CType(FindControlRecursive(plhCreate, plhCreate.ID & "_" & Constants.ControlId_Email), RadTextBox)
            blnUpdateEmail = (Not txtEmail Is Nothing)

            If blnUpdateEmail Then
                If Not IsValidUserAttribute(Constants.User_Email, plhCreate) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Email, plhCreate)
                End If
            End If

            Dim txtPassword As RadTextBox = CType(FindControlRecursive(plhCreate, plhCreate.ID & "_" & Constants.ControlId_Password1), RadTextBox)
            Dim txtPassword2 As RadTextBox = CType(FindControlRecursive(plhCreate, plhCreate.ID & "_" & Constants.ControlId_Password2), RadTextBox)
            blnUpdatePassword = (Not txtPassword Is Nothing AndAlso Not txtPassword2 Is Nothing)

            If blnUpdatePassword Then
                If Not IsValidUserAttribute(Constants.User_Password1, plhCreate) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Password1, plhCreate)
                End If
                If Not IsValidUserAttribute(Constants.User_Password2, plhCreate) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Password2, plhCreate)
                End If
            End If

            Dim txtFirstName As RadTextBox = CType(FindControlRecursive(plhCreate, plhCreate.ID & "_" & Constants.ControlId_Firstname), RadTextBox)
            blnUpdateFirstname = (Not txtFirstName Is Nothing)

            If blnUpdateFirstname Then
                If Not IsValidUserAttribute(Constants.User_Firstname, plhCreate) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Firstname, plhCreate)
                End If
            End If

            Dim txtLastName As RadTextBox = CType(FindControlRecursive(plhCreate, plhCreate.ID & "_" & Constants.ControlId_Lastname), RadTextBox)
            blnUpdateLastname = (Not txtLastName Is Nothing)

            If blnUpdateLastname Then
                If Not IsValidUserAttribute(Constants.User_Lastname, plhCreate) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Lastname, plhCreate)
                End If
            End If

            Dim txtDisplayName As RadTextBox = CType(FindControlRecursive(plhCreate, plhCreate.ID & "_" & Constants.ControlId_Displayname), RadTextBox)
            blnUpdateDisplayname = (Not txtDisplayName Is Nothing)

            If blnUpdateDisplayname Then
                If Not IsValidUserAttribute(Constants.User_Displayname, plhCreate) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Displayname, plhCreate)
                End If
            End If

            For Each itemProp As String In GetPropertiesFromTempate(Me.Template_CreateAccount(CurrentLocale))
                Try
                    Dim prop As ProfilePropertyDefinition = ProfileController.GetPropertyDefinitionByName(itemProp.Substring(2), PortalId) 'itemprop comes in the form U:Propertyname or P:Propertyname
                    If Not prop Is Nothing Then
                        If Not IsValidProperty(Nothing, prop, plhCreate) Then
                            strMessage += "Error"
                            AddErrorIndicator(prop.PropertyDefinitionId.ToString, plhCreate)
                        End If
                    End If
                Catch
                End Try
            Next

            If strMessage.Length > 0 Then
                Me.pnlCreateUserError.Visible = True
                Me.pnlCreateUserIntro.Visible = False
                Me.pnlCreateUserSuccess.Visible = False
                Me.lblCreateUserError.Text = "<ul><li>" & GetString("FieldsRequired", LocalResourceFile) & "</li></ul>"
                Exit Sub
            End If

            'all good so far, let's update the profile

            Dim oUser As New UserInfo

            If PortalSettings.UserRegistration = PortalRegistrationType.PublicRegistration Then
                oUser.Membership.Approved = True
            Else
                oUser.Membership.Approved = False
            End If

            oUser.AffiliateID = Null.NullInteger
            oUser.PortalID = PortalSettings.PortalId
            oUser.Username = ""
            oUser.DisplayName = ""
            oUser.Email = ""
            oUser.Membership.Password = ""

            'set username depending on setting
            Select Case UsernameMode
                Case UsernameUpdateMode.Email
                    If blnUpdateEmail Then
                        oUser.Username = txtEmail.Text.Trim
                    End If
                Case UsernameUpdateMode.FirstLetterLastname
                    If blnUpdateLastname AndAlso blnUpdateFirstname Then
                        oUser.Username = txtFirstName.Text.Trim.Substring(0, 1) & "." & txtLastName.Text
                    End If
                Case UsernameUpdateMode.FirstnameLastname
                    If blnUpdateLastname AndAlso blnUpdateFirstname Then
                        oUser.Username = txtFirstName.Text & "." & txtLastName.Text
                    End If
                Case UsernameUpdateMode.Lastname
                    If blnUpdateLastname Then
                        oUser.Username = txtLastName.Text
                    End If
                Case UsernameUpdateMode.UserSelect
                    If blnUpdateUsername Then
                        oUser.Username = txtUsername.Text
                    End If
            End Select

            'set displayname depending on setting
            Select Case DisplaynameMode
                Case DisplaynameUpdateMode.Email
                    If blnUpdateEmail Then
                        oUser.DisplayName = txtEmail.Text.Trim
                    End If
                Case DisplaynameUpdateMode.FirstLetterLastname
                    If blnUpdateLastname AndAlso blnUpdateFirstname Then
                        oUser.DisplayName = txtFirstName.Text.Trim.Substring(0, 1) & ". " & txtLastName.Text
                    End If
                Case DisplaynameUpdateMode.FirstnameLastname
                    If blnUpdateLastname AndAlso blnUpdateFirstname Then
                        oUser.DisplayName = txtFirstName.Text & " " & txtLastName.Text
                    End If
                Case DisplaynameUpdateMode.Lastname
                    If blnUpdateLastname Then
                        oUser.DisplayName = txtLastName.Text
                    End If
                Case DisplaynameUpdateMode.UserSelect
                    If blnUpdateDisplayname Then
                        oUser.DisplayName = txtDisplayName.Text
                    End If
            End Select

            If blnUpdateDisplayname AndAlso Not IsRegisterMode() Then
                oUser.DisplayName = txtDisplayName.Text
            End If

            'try updating firstname
            If blnUpdateFirstname Then
                oUser.FirstName = txtFirstName.Text
            End If

            'try updating lastname
            If blnUpdateLastname Then
                oUser.LastName = txtLastName.Text
            End If

            If blnUpdateEmail Then
                oUser.Email = txtEmail.Text
            End If

            'try updating password
            If blnUpdatePassword Then

                If txtPassword.Text = txtPassword2.Text Then
                    If Not UserController.ValidatePassword(txtPassword.Text) Then

                        Me.pnlCreateUserError.Visible = True
                        Me.pnlCreateUserIntro.Visible = False
                        Me.pnlCreateUserSuccess.Visible = False
                        Me.lblCreateUserError.Text = "<ul><li>" & GetString("PasswordPoliciesError", LocalResourceFile) & "</li></ul>"
                        Exit Sub

                    End If
                Else

                    Me.pnlCreateUserError.Visible = True
                    Me.pnlCreateUserIntro.Visible = False
                    Me.pnlCreateUserSuccess.Visible = False
                    Me.lblCreateUserError.Text = "<ul><li>" & GetString("PasswordMatchError", LocalResourceFile) & "</li></ul>"
                    Exit Sub

                End If

                oUser.Membership.Password = txtPassword.Text

            End If

            'try updating displayname

            If oUser.Username = "" Or oUser.Email = "" Or oUser.DisplayName = "" Or oUser.Membership.Password = "" Then
                'template must be setup up wrong
                Me.pnlCreateUserError.Visible = True
                Me.pnlCreateUserIntro.Visible = False
                Me.pnlCreateUserSuccess.Visible = False
                Me.lblCreateUserError.Text = "<ul><li>" & GetString("TemplateError", LocalResourceFile) & "</li></ul>"
            End If


            'set up profile
            oUser.Profile = New UserProfile
            oUser.Profile.InitialiseProfile(PortalSettings.PortalId, True)

            'see if we can create the account
            Dim createStatus As UserCreateStatus = UserController.CreateUser(oUser)
            If createStatus <> UserCreateStatus.Success Then

                Select Case createStatus
                    Case UserCreateStatus.UsernameAlreadyExists
                        Select Case UsernameMode
                            Case UsernameUpdateMode.UserSelect
                                strMessage = Localization.GetString("UsernameAlreadyExists", Me.SharedResourcefile)
                            Case UsernameUpdateMode.Email
                                strMessage = Localization.GetString("DuplicateEmail", Me.SharedResourcefile)
                            Case UsernameUpdateMode.FirstnameLastname, UsernameUpdateMode.FirstLetterLastname, UsernameUpdateMode.Lastname
                                strMessage = Localization.GetString("NameAlreadyExists", Me.SharedResourcefile)
                        End Select
                    Case Else
                        strMessage = String.Format(GetString("UserCreateError", Me.LocalResourceFile), createStatus.ToString)
                End Select

                If strMessage <> "" Then
                    strMessage = "<li>" & strMessage & "</li>"
                Else
                    strMessage = "<li>" & createStatus.ToString & "</li>"
                End If

                Me.pnlCreateUserError.Visible = True
                Me.pnlCreateUserIntro.Visible = False
                Me.pnlCreateUserSuccess.Visible = False
                Me.lblCreateUserError.Text = "<ul>" & strMessage & "</ul>"

                Exit Sub

            End If

            If blnUpdateDisplayname AndAlso Not IsRegisterMode() Then
                oUser.DisplayName = txtDisplayName.Text
            End If

            'try updating firstname
            If blnUpdateFirstname Then
                oUser.FirstName = txtFirstName.Text
                oUser.Profile.FirstName = oUser.FirstName
            End If

            'try updating lastname
            If blnUpdateLastname Then
                oUser.LastName = txtLastName.Text
                oUser.Profile.LastName = oUser.LastName
            End If

            If blnUpdateEmail Then
                oUser.Email = txtEmail.Text
            End If

            oUser.Profile.PreferredLocale = PortalSettings.DefaultLanguage
            oUser.Profile.TimeZone = PortalSettings.TimeZoneOffset

            UserController.UpdateUser(PortalId, oUser)

            'add to role
            If ctlRoles.SelectedNode.Value <> PortalSettings.RegisteredRoleId.ToString Then
                If IsNumeric(ctlRoles.SelectedNode.Value) Then
                    Dim roleid As Integer = Convert.ToInt32(ctlRoles.SelectedNode.Value)
                    Try
                        Dim rc As New Security.Roles.RoleController
                        Dim role As RoleInfo = rc.GetRole(roleid, PortalId)
                        If Not role Is Nothing Then
                            rc.AddUserRole(PortalId, oUser.UserID, role.RoleID, Null.NullDate)
                        End If
                    Catch
                    End Try
                End If
            End If

            Me.pnlCreateUserError.Visible = False
            Me.pnlCreateUserIntro.Visible = False
            Me.pnlCreateUserSuccess.Visible = True
            Me.lblCreateUserSuccess.Text = "<ul><li>" & GetString("AccountCreated", LocalResourceFile) & "</li></ul>"

            pnlCreateUser_Step1.Visible = False
            pnlCreateUser_Step2.Visible = True

            BindUserCreateNotification(oUser)

            btnNotifyCreateUser.CommandArgument = oUser.UserID.ToString
            btnNotifyCreateUserSkip.CommandArgument = oUser.UserID.ToString

            ClearCache()

            ProcessFormTemplate(plhCreate, Template_CreateAccount(CurrentLocale), Nothing, _PageNeedsToPostback)

        End Sub

        Protected Sub btnNotifyCreateUser_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnNotifyCreateUser.Click

            Dim intUser As Integer = Convert.ToInt32(CType(sender, Button).CommandArgument)
            Dim intRole As Integer = Null.NullInteger

            If ctlRoles.SelectedNode.Value <> PortalSettings.RegisteredRoleId.ToString Then
                If IsNumeric(ctlRoles.SelectedNode.Value) Then
                    Dim roleid As Integer = Convert.ToInt32(ctlRoles.SelectedNode.Value)
                    intRole = roleid
                End If
            End If

            Dim oUser As UserInfo = UserController.GetUserById(PortalId, intUser)
            Dim strPassword As String = MembershipProvider.Instance().GetPassword(oUser, "")
            Dim strBody As String = txtUserCreatedBody.Content.Replace(GetString("HiddenPassword", LocalResourceFile), strPassword)
            Dim strSubject As String = txtUserCreatedSubject.Text
            If strSubject = "" Then
                strSubject = txtUserCreatedSubject.EmptyMessage.Replace(GetString("SubjectPrefix", LocalResourceFile), "")
            End If

            Mail.SendEmail(PortalSettings.Email, User.Email, strSubject, strBody)

            If intRole <> Null.NullInteger Then
                Response.Redirect(NavigateURL(TabId, "", "RoleId=" & intRole.ToString, "uid=" & intUser.ToString))
            Else
                Response.Redirect(NavigateURL(TabId, "", "uid=" & intUser.ToString))
            End If

        End Sub

        Protected Sub btnNotifyCreateUserSkip_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnNotifyCreateUserSkip.Click

            Dim intUser As Integer = Convert.ToInt32(CType(sender, Button).CommandArgument)
            Dim intRole As Integer = Null.NullInteger

            If ctlRoles.SelectedNode.Value <> PortalSettings.RegisteredRoleId.ToString Then
                If IsNumeric(ctlRoles.SelectedNode.Value) Then
                    Dim roleid As Integer = Convert.ToInt32(ctlRoles.SelectedNode.Value)
                    intRole = roleid
                End If
            End If

            If intRole <> Null.NullInteger Then
                Response.Redirect(NavigateURL(TabId, "", "RoleId=" & intRole.ToString, "uid=" & intUser.ToString))
            Else
                Response.Redirect(NavigateURL(TabId, "", "uid=" & intUser.ToString))
            End If

        End Sub

        Protected Sub ctlRoles_NodeClick(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadTreeNodeEventArgs) Handles ctlRoles.NodeClick
            If (e.Node.Attributes("IsGroup") = False) Then
                Session.Remove("dnnWerk_UserSearchTerm")
                txtSearch.Text = ""
                pnlGrid.Visible = True
                pnlUser.Visible = False
                pnlCreate.Visible = False
                grdUsers.Rebind()
                
                If AllowCreate Then
                    btnAction.Enabled = True
                    btnAction.CommandName = "Create"
                    btnAction.Text = GetString("CreateUser", LocalResourceFile)
                Else
                    btnAction.CommandName = ""
                    btnAction.Text = ""
                    btnAction.Enabled = False
                End If

            End If
        End Sub

        Protected Sub grdUsers_ItemDataBound(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridItemEventArgs) Handles grdUsers.ItemDataBound
            If e.Item.ItemType = GridItemType.AlternatingItem Or e.Item.ItemType = GridItemType.Item Then

                Try

                    Dim dataBoundItem As GridDataItem = e.Item


                    'Dim objUser As UserInfo = CType(e.Item.DataItem, UserInfo)
                    Dim row As DataRowView = CType(e.Item.DataItem, DataRowView)
                    Dim intUser As String = Convert.ToInt32(row("UserID"))

                    Dim ctlMenu As RadMenu = CType(e.Item.FindControl("ctlActionMenu"), RadMenu)
                    If Not ctlMenu Is Nothing Then

                        'build action menu for useraccounts 
                        Dim rootItem As RadMenuItem = ctlMenu.Items(0)
                        rootItem.Text = GetString("Actions", LocalResourceFile)

                        If ctlRoles.SelectedNode Is Nothing Then 'reports mode

                            Dim itemEdit As New RadMenuItem(GetString("EditAccount", LocalResourceFile))
                            itemEdit.Attributes.Add("cmd", "edit")
                            itemEdit.Value = intUser.ToString
                            itemEdit.ImageUrl = "~/images/edit.gif"
                            itemEdit.NavigateUrl = NavigateURL(TabId, "", "uid=" & row("UserID"), "RoleId=" & PortalSettings.RegisteredRoleId.ToString)
                            itemEdit.Attributes.Add("usn", row("Username"))
                            itemEdit.Attributes.Add("pid", row("PortalId"))
                            itemEdit.Attributes.Add("mid", ModuleId)
                            rootItem.Items.Add(itemEdit)


                            If AllowDelete Then

                                If intUser <> PortalSettings.AdministratorId Then
                                    Dim itemDelete As New RadMenuItem(GetString("DeleteAccount", LocalResourceFile))
                                    itemDelete.Attributes.Add("cmd", "delete")
                                    itemDelete.Attributes.Add("usn", row("Username"))
                                    itemDelete.Attributes.Add("pid", row("PortalId"))
                                    itemDelete.Attributes.Add("mid", ModuleId)
                                    itemDelete.Value = intUser.ToString
                                    itemDelete.ImageUrl = "~/images/action_delete.gif"
                                    rootItem.Items.Add(itemDelete)
                                End If

                            End If
                            

                            If UserInfo.IsInRole(PortalSettings.AdministratorRoleName) Then
                                Dim itemImp As New RadMenuItem(GetString("ImpersonateAccount", LocalResourceFile))
                                itemImp.Attributes.Add("cmd", "impersonate")
                                itemImp.Attributes.Add("usn", row("Username"))
                                itemImp.Attributes.Add("pid", row("PortalId"))
                                itemImp.Attributes.Add("mid", ModuleId)
                                itemImp.Value = intUser.ToString
                                itemImp.ImageUrl = "~/images/icon_hostusers_16px.gif"
                                rootItem.Items.Add(itemImp)
                            End If


                        Else 'role filter mode

                            If (Not ctlRoles.SelectedNode Is Nothing AndAlso ctlRoles.SelectedNode.Value = "-2") Then 'recycle bin mode


                                Dim itemRecyle As New RadMenuItem(GetString("RestoreAccount", LocalResourceFile))
                                itemRecyle.Attributes.Add("cmd", "restore")
                                itemRecyle.Value = intUser.ToString
                                itemRecyle.ImageUrl = "~/images/restore.gif"
                                itemRecyle.Attributes.Add("usn", row("Username"))
                                itemRecyle.Attributes.Add("pid", row("PortalId"))
                                itemRecyle.Attributes.Add("mid", ModuleId)
                                rootItem.Items.Add(itemRecyle)


                                If AllowHardDelete Then
                                    If intUser <> PortalSettings.AdministratorId Then
                                        Dim itemDelete As New RadMenuItem(GetString("HardDeleteAccount", LocalResourceFile))
                                        itemDelete.Attributes.Add("cmd", "harddelete")
                                        itemDelete.Attributes.Add("usn", row("Username"))
                                        itemDelete.Attributes.Add("pid", row("PortalId"))
                                        itemDelete.Attributes.Add("mid", ModuleId)
                                        itemDelete.Value = intUser.ToString
                                        itemDelete.ImageUrl = "~/images/action_delete.gif"
                                        rootItem.Items.Add(itemDelete)
                                    End If
                                End If
                             


                            Else

                                Dim itemEdit As New RadMenuItem(GetString("EditAccount", LocalResourceFile))
                                itemEdit.Attributes.Add("cmd", "edit")
                                itemEdit.Value = intUser.ToString
                                itemEdit.ImageUrl = "~/images/edit.gif"
                                itemEdit.NavigateUrl = NavigateURL(TabId, "", "uid=" & row("UserID"), "RoleId=" & ctlRoles.SelectedNode.Value)
                                itemEdit.Attributes.Add("usn", row("Username"))
                                itemEdit.Attributes.Add("pid", row("PortalId"))
                                itemEdit.Attributes.Add("mid", ModuleId)
                                rootItem.Items.Add(itemEdit)


                                If AllowDelete Then
                                    If intUser <> PortalSettings.AdministratorId Then
                                        Dim itemDelete As New RadMenuItem(GetString("DeleteAccount", LocalResourceFile))
                                        itemDelete.Attributes.Add("cmd", "delete")
                                        itemDelete.Attributes.Add("usn", row("Username"))
                                        itemDelete.Attributes.Add("pid", row("PortalId"))
                                        itemDelete.Attributes.Add("mid", ModuleId)
                                        itemDelete.Value = intUser.ToString
                                        itemDelete.ImageUrl = "~/images/action_delete.gif"
                                        rootItem.Items.Add(itemDelete)
                                    End If
                                End If


                                If UserInfo.IsInRole(PortalSettings.AdministratorRoleName) Then
                                    Dim itemImp As New RadMenuItem(GetString("ImpersonateAccount", LocalResourceFile))
                                    itemImp.Attributes.Add("cmd", "impersonate")
                                    itemImp.Attributes.Add("usn", row("Username"))
                                    itemImp.Attributes.Add("pid", row("PortalId"))
                                    itemImp.Attributes.Add("mid", ModuleId)
                                    itemImp.Value = intUser.ToString
                                    itemImp.ImageUrl = "~/images/icon_hostusers_16px.gif"
                                    rootItem.Items.Add(itemImp)
                                End If

                            End If

                        End If

                    End If


                Catch ex As Exception

                End Try

            End If
        End Sub

        Protected Sub grdUsers_NeedDataSource(ByVal source As Object, ByVal e As Telerik.Web.UI.GridNeedDataSourceEventArgs) Handles grdUsers.NeedDataSource
            BindUsers()
        End Sub

        Protected Sub chkAutoGeneratePassword_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles chkAutoGeneratePassword.CheckedChanged
            pnlPassword1.Visible = (chkAutoGeneratePassword.Checked = False)
            pnlPassword2.Visible = (chkAutoGeneratePassword.Checked = False)
        End Sub

        Protected Sub btnUpdatePassword_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdatePassword.Click

            Dim blnProceed As Boolean = True

            If chkAutoGeneratePassword.Checked = False Then

                'verifiy passwords have been entered and both passwords match

                If txtPassword1.Text = txtPassword2.Text Then
                    If UserController.ValidatePassword(txtPassword1.Text) Then
                        blnProceed = True
                    Else
                        Me.lblPasswordError.Text = "<ul><li>" & GetString("PasswordPoliciesError", LocalResourceFile) & "</li></ul>"
                        blnProceed = False
                    End If
                Else
                    Me.lblPasswordError.Text = "<ul><li>" & GetString("PasswordMatchError", LocalResourceFile) & "</li></ul>"
                    blnProceed = False
                End If

            End If

            If blnProceed = False Then

                Me.pnlPasswordError.Visible = True
                Me.pnlPasswordSuccess.Visible = False
                Me.pnlPasswordIntro.Visible = False

            Else

                Me.pnlPasswordError.Visible = False
                Me.pnlPasswordSuccess.Visible = True
                Me.pnlPasswordIntro.Visible = False

                Dim strPassword As String = ""
                If chkAutoGeneratePassword.Checked = False Then
                    strPassword = txtPassword1.Text
                Else
                    strPassword = UserController.GeneratePassword(7)
                End If

                If UserController.ChangePassword(User, "", strPassword) Then

                    lblPasswordSucess.Text = "<ul><li>" & GetString("PasswordReset", LocalResourceFile) & "</li></ul>"

                    pnlPassword_Step1.Visible = False
                    pnlPassword_Step2.Visible = True

                    BindPasswordNotification()

                Else

                    Me.lblPasswordError.Text = "<ul><li>" & GetString("PasswordResetError", LocalResourceFile) & "</li></ul>"
                    Me.pnlPasswordError.Visible = True
                    Me.pnlPasswordSuccess.Visible = False
                    Me.pnlPasswordIntro.Visible = False

                End If

            End If

        End Sub

        Protected Sub btnNotifyPassword_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnNotifyPassword.Click

            Dim strPassword As String = MembershipProvider.Instance().GetPassword(User, "")
            Dim strBody As String = txtNotifyPasswordBody.Content.Replace(GetString("HiddenPassword", LocalResourceFile), strPassword)

            Dim strSubject As String = txtNotifyPasswordSubject.Text
            If strSubject = "" Then
                strSubject = txtNotifyPasswordSubject.EmptyMessage.Replace(GetString("SubjectPrefix", LocalResourceFile), "")
            End If

            Mail.SendEmail(PortalSettings.Email, User.Email, strSubject, strBody)
            Me.lblPasswordSucess.Text = "<ul><li>" & GetString("UserNotifiedPassword", LocalResourceFile) & "</li></ul>"

            Me.pnlPasswordSuccess.Visible = True
            Me.pnlPasswordError.Visible = False
            Me.pnlPasswordIntro.Visible = False

            pnlPassword_Step1.Visible = True
            pnlPassword_Step2.Visible = False

            chkAutoGeneratePassword.Checked = False
            pnlPassword1.Visible = True
            pnlPassword2.Visible = True
            txtPassword1.Text = ""
            txtPassword2.Text = ""

        End Sub

        Protected Sub btnNotifyPasswordSkip_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnNotifyPasswordSkip.Click

            'reset password tab
            pnlPassword_Step1.Visible = True
            pnlPassword_Step2.Visible = False

            chkAutoGeneratePassword.Checked = False
            pnlPassword1.Visible = True
            pnlPassword2.Visible = True
            txtPassword1.Text = ""
            txtPassword2.Text = ""

            pnlPasswordIntro.Visible = True
            pnlPasswordError.Visible = False
            pnlPasswordSuccess.Visible = False


        End Sub

        Protected Sub btnUpdateAccount_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdateAccount.Click
            UpdateAccount()
            ProcessFormTemplate(plhUser, Template_EditAccount(CurrentLocale), User, _PageNeedsToPostback)
        End Sub

        Protected Sub btnUpdateProfile_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdateProfile.Click
            UpdateProfile()
            ProcessFormTemplate(plhProfile, Template_EditProfile(CurrentLocale), User, _PageNeedsToPostback)
        End Sub

        Private Sub LogonUser(ByVal objUser As UserInfo)

            If Not objUser Is Nothing Then

                If UserInfo IsNot Nothing Then
                    DataCache.ClearUserCache(Me.PortalSettings.PortalId, Context.User.Identity.Name)
                End If

                Dim objPortalSecurity As New PortalSecurity
                objPortalSecurity.SignOut()

                Dim password As String = UserController.GetPassword(objUser, "")

                Dim status As DotNetNuke.Security.Membership.UserLoginStatus
                UserController.UserLogin(PortalSettings.PortalId, objUser.Username, password, "", PortalSettings.PortalName, Request.UserHostAddress, status, False)


                Response.Redirect(NavigateURL(PortalSettings.HomeTabId))

            End If

        End Sub

        Protected Sub ctlAjax_AjaxRequest(ByVal sender As Object, ByVal e As Telerik.Web.UI.AjaxRequestEventArgs) Handles ctlAjax.AjaxRequest

            Dim cmd As String = Null.NullString
            Dim intUser As Integer = Null.NullInteger
            Dim objUser As UserInfo = Nothing
            Try
                cmd = e.Argument.Split(Char.Parse("|"))(0)
                intUser = Convert.ToInt32(e.Argument.Split(Char.Parse("|"))(1))
                objUser = UserController.GetUserById(PortalId, intUser)
            Catch
            End Try

            If cmd <> Null.NullString AndAlso intUser <> Null.NullInteger AndAlso (Not objUser Is Nothing) Then

                Dim strResponse As String = ""
                Select Case cmd

                    Case "impersonate"

                        LogonUser(objUser)

                    Case "edit"

                        BindUser(intUser)

                    Case "restore"

                        RestoreAccount(objUser.UserID)
                        Response.Redirect(NavigateURL(TabId, "", "RoleId=" & PortalSettings.RegisteredRoleId.ToString, "uid=" & intUser.ToString, "Restored=true"))

                    Case "harddelete"

                        'Let's see if we can delete the account
                        Dim blnCanDelete As Boolean = True

                        Dim ctrlPortals As New PortalController
                        Dim portals As ArrayList = ctrlPortals.GetPortals()
                        For Each oPortal As PortalInfo In portals
                            Dim pUser As UserInfo = UserController.GetUserById(oPortal.PortalID, objUser.UserID)
                            If Not pUser Is Nothing Then
                                If pUser.IsDeleted = False Then
                                    'user is in use in another portal, we can't delete it
                                    blnCanDelete = False                                  
                                    Exit For
                                End If
                            End If
                        Next

                        If blnCanDelete Then
                            HardDeleteAccount(objUser.UserID, objUser.Username)
                            strResponse = GetString("UserHardDelete", LocalResourceFile)
                        Else
                            strResponse = GetString("SingleUserHardDeleteError", LocalResourceFile)
                        End If

                        ctlAjax.ResponseScripts.Add("radalert('" & strResponse & "');")
                        grdUsers.Rebind()

                    Case "delete"

                        If UserController.DeleteUser(objUser, False, False) Then
                            ClearCache()
                            strResponse = "User " & objUser.Username & " deleted!"
                        Else
                            strResponse = "User " & objUser.Username & " could not be deleted!"
                        End If

                        ctlAjax.ResponseScripts.Add("radalert('" & strResponse & "');")
                        grdUsers.Rebind()


                    Case "unlock"

                        If UserController.UnLockUser(objUser) Then
                            strResponse = "User " & objUser.Username & " authorized!"
                        Else
                            strResponse = "User " & objUser.Username & " could not be authorized!"
                        End If

                        grdUsers.Rebind()
                        ctlAjax.ResponseScripts.Add("radalert('" & strResponse & "');")

                End Select




            Else

                If cmd.ToLower = "emptybin" Then
                    If UserInfo.IsSuperUser Then

                        Dim intDeleted As Integer = 0
                        Dim intError As Integer = 0

                        Dim ds As DataSet = GetUserList()
                        If Not ds Is Nothing Then

                            For Each row As DataRow In ds.Tables(0).Rows

                                Dim iUser As Integer = Null.NullInteger
                                Integer.TryParse(row("UserID"), iUser)

                                If iUser <> Null.NullInteger Then
                                    Dim oUser As UserInfo = UserController.GetUserById(PortalId, iUser)
                                    If Not oUser Is Nothing Then

                                        'account found. Let's see if we can delete it
                                        Dim blnCanDelete As Boolean = True

                                        Dim ctrlPortals As New PortalController
                                        Dim portals As ArrayList = ctrlPortals.GetPortals()
                                        For Each oPortal As PortalInfo In portals
                                            Dim pUser As UserInfo = UserController.GetUserById(oPortal.PortalID, oUser.UserID)
                                            If Not pUser Is Nothing Then
                                                If pUser.IsDeleted = False Then
                                                    'user is in use in another portal, we can't delete it
                                                    blnCanDelete = False
                                                    intError += 1
                                                    Exit For
                                                End If
                                            End If
                                        Next

                                        If blnCanDelete Then
                                            HardDeleteAccount(oUser.UserID, oUser.Username)
                                            intDeleted += 1
                                        End If

                                    End If

                                End If

                            Next
                        End If

                        Dim strResponse As String = ""

                        If intDeleted > 0 Then
                            strResponse = String.Format(GetString("ResultHardDelete", LocalResourceFile), intDeleted.ToString)
                        Else
                            strResponse = GetString("ResultNoHardDelete", LocalResourceFile)
                        End If

                        If intError > 0 Then
                            strResponse += String.Format(GetString("ResultHardDeleteError", LocalResourceFile), intDeleted.ToString)
                        End If

                        ctlAjax.ResponseScripts.Add("radalert('" & strResponse & "');")
                        grdUsers.Rebind()

                    End If
                End If
                'scripting error
                'todo: handle error
            End If

        End Sub

        Protected Sub cmdDeleteTestaccounts_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdDeleteTestaccounts.Click

            For i As Integer = 1 To ctlCount.Value

                Dim objUser As UserInfo = Nothing
                Try
                    objUser = UserController.GetUserByName(PortalId, "Test_" & i.ToString)
                Catch
                End Try

                If Not objUser Is Nothing Then
                    UserController.DeleteUser(objUser, False, False)
                End If

            Next

        End Sub

        Protected Sub cmdCreateTestAccounts_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdCreateTestAccounts.Click

            Dim firstnames As String() = New String() {"John", "Dan", "Tom", "Charles", "Henry", "Walter", "George", "Bruce", "Charly", "Sam"}
            Dim lastnames As String() = New String() {"Fuller", "Doe", "Bush", "Dickens", "Ford", "Spade", "Myer", "Cloony", "Willis", "Jackson"}

            For i As Integer = 1 To ctlCount.Value

                Dim objUser As New UserInfo
                objUser.Username = "Test_" & i.ToString
                objUser.Email = "Test_" & i.ToString & "@testdomain.local"
                objUser.Membership.Password = "password"

                Dim objRandom As New Random()
                Dim posFirstname As Integer = objRandom.Next(0, 9)
                Dim posLastname As Integer = objRandom.Next(0, 9)
                Dim day As Integer = objRandom.Next(1, 30)
                Dim month As Integer = objRandom.Next(1, 12)
                Dim year As Integer = objRandom.Next(1980, 2010)
                Dim dtCreated As Date = New Date(year, month, day)

                objUser.FirstName = firstnames(posFirstname).ToString
                objUser.LastName = lastnames(posLastname).ToString
                objUser.PortalID = PortalId
                objUser.AffiliateID = Null.NullInteger
                objUser.DisplayName = firstnames(posFirstname).ToString & " " & lastnames(posLastname).ToString
                objUser.Membership.CreatedDate = dtCreated

                objUser.Profile.InitialiseProfile(True)

                Try
                    UserController.CreateUser(objUser)
                    objUser.FirstName = firstnames(posFirstname).ToString
                    objUser.LastName = lastnames(posLastname).ToString
                    objUser.Profile.FirstName = firstnames(posFirstname).ToString
                    objUser.Profile.LastName = lastnames(posLastname).ToString
                    UserController.UpdateUser(PortalId, objUser)
                Catch
                End Try

            Next

        End Sub

        Protected Sub btnForcePasswordChange_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnForcePasswordChange.Click
            Dim oUser As UserInfo = User
            oUser.Membership.UpdatePassword = True
            UserController.UpdateUser(PortalId, oUser)
            BindUser(oUser.UserID)
        End Sub

        Protected Sub btnAuthorize_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAuthorize.Click
            Dim oUser As UserInfo = User
            oUser.Membership.Approved = True
            UserController.UpdateUser(PortalId, oUser)
            BindUser(oUser.UserID)
        End Sub

        Protected Sub btnUnlockAccount_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUnlockAccount.Click
            Dim oUser As UserInfo = User
            oUser.Membership.LockedOut = False
            UserController.UpdateUser(PortalId, oUser)
            BindUser(oUser.UserID)
        End Sub

        Protected Sub btnSendEmail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSendEmail.Click

            Try

                Dim strPassword As String = MembershipProvider.Instance().GetPassword(User, "")
                Dim strBody As String = txtEmailUserBody.Content.Replace(GetString("HiddenPassword", LocalResourceFile), strPassword)

                Dim strSubject As String = txtEmailUserSubject.Text
                If strSubject = "" Then
                    strSubject = txtEmailUserSubject.EmptyMessage.Replace(GetString("SubjectPrefix", LocalResourceFile), "")
                End If

                Mail.SendEmail(PortalSettings.Email, User.Email, strSubject, strBody)

                pnlEmailIntro.Visible = False
                pnlEmailError.Visible = False
                pnlEmailSuccess.Visible = True
                lblEmailSuccess.Text = "<ul><li>" & GetString("MessageSentToUser", LocalResourceFile) & "</li></ul>"

            Catch ex As Exception

                pnlEmailIntro.Visible = False
                pnlEmailError.Visible = True
                pnlEmailSuccess.Visible = False
                lblEmailError.Text = "<ul><li>" & GetString("MessageSentToUserError", LocalResourceFile) & "</li></ul>"

            End Try

        End Sub

        Protected Sub grdUserRoles_ItemDataBound(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridItemEventArgs) Handles grdUserRoles.ItemDataBound
            If e.Item.ItemType = GridItemType.AlternatingItem Or e.Item.ItemType = GridItemType.Item Then

                Dim dataBoundItem As GridDataItem = CType(e.Item, GridDataItem)

                Dim expiryDate As Date = Date.Parse(dataBoundItem("col_ExpiryDate").Text)
                If expiryDate = Null.NullDate Then
                    dataBoundItem("col_ExpiryDate").Text = "-"
                Else
                    dataBoundItem("col_ExpiryDate").Text = expiryDate.ToShortDateString
                End If

                Dim effectiveDate As Date = Date.Parse(dataBoundItem("col_EffectiveDate").Text)
                If effectiveDate = Null.NullDate Then
                    dataBoundItem("col_EffectiveDate").Text = User.Membership.CreatedDate.ToShortDateString
                Else
                    dataBoundItem("col_EffectiveDate").Text = effectiveDate.ToShortDateString
                End If

                Dim btn As ImageButton = CType(dataBoundItem("removeCol").FindControl("btnDeleteUserRole"), ImageButton)
                btn.ImageUrl = ResolveUrl("~/images/delete.gif")

                If btn.CommandArgument = PortalSettings.RegisteredRoleId.ToString Then
                    btn.Visible = False
                End If

                If btn.CommandArgument = PortalSettings.AdministratorRoleId.ToString Then
                    btn.Visible = (User.UserID <> PortalSettings.AdministratorId)
                End If


            End If
        End Sub

        Protected Sub grdUserRoles_NeedDataSource(ByVal source As Object, ByVal e As Telerik.Web.UI.GridNeedDataSourceEventArgs) Handles grdUserRoles.NeedDataSource

            Dim roleController As New Security.Roles.RoleController
            Dim userRoles As ArrayList = roleController.GetUserRoles(PortalId, User.UserID)

            grdUserRoles.DataSource = userRoles

        End Sub

        Protected Sub btnDeleteUserRole_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)

            Dim roleId As Integer = Convert.ToInt32(CType(sender, ImageButton).CommandArgument)
            Dim roleController As New RoleController
            roleController.DeleteUserRole(PortalId, User.UserID, roleId)

            DataCache.RemoveCache("DNNWERK_USERLIST_ROLEID" & roleId.ToString)

            Dim strRole As String = roleController.GetRole(roleId, PortalId).RoleName
            BindRoleRemoveNotification(strRole)

            pnlRoleChange_Step1.Visible = False
            pnlRoleChange_Step2.Visible = True
            lblRolesIntro.Text = GetString("NotifyUserQuestion", LocalResourceFile)
            btnNotifyRole.CommandArgument = "remove"
            btnNotifyRoleSkip.CommandArgument = "remove"

            Me.lblRolesSuccess.Text = "<ul><li>" & GetString("UserRemovedFromRole", LocalResourceFile) & "</li></ul>"
            Me.pnlRolesSuccess.Visible = True
            Me.pnlRolesIntro.Visible = False
            Me.pnlRolesError.Visible = False

        End Sub

        Protected Sub btnAddToRole_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddToRole.Click

            Dim roleController As New RoleController

            Dim effectiveDate As Date = Date.Now
            If Not ctlRoleDatFrom.DbSelectedDate Is Nothing Then
                effectiveDate = ctlRoleDatFrom.DbSelectedDate
            End If

            Dim expiryDate As Date = Null.NullDate
            If Not ctlRoleDateTo.DbSelectedDate Is Nothing Then
                expiryDate = ctlRoleDateTo.DbSelectedDate
            End If

            Dim roleId As Integer = Null.NullInteger
            If drpRoles.SelectedItem.Value <> "-1" Then
                roleId = Convert.ToInt32(drpRoles.SelectedItem.Value)
            End If

            If roleId <> Null.NullInteger Then

                roleController.AddUserRole(PortalId, User.UserID, roleId, effectiveDate, expiryDate)
                BindRoleAddNotification(drpRoles.SelectedItem.Text, effectiveDate, expiryDate)

                DataCache.RemoveCache("DNNWERK_USERLIST_ROLEID" & roleId.ToString)

                pnlRoleChange_Step1.Visible = False
                pnlRoleChange_Step2.Visible = True
                lblRolesIntro.Text = GetString("NotifyUserQuestion", LocalResourceFile)

                btnNotifyRole.CommandArgument = "add"
                btnNotifyRoleSkip.CommandArgument = "add"

                Me.lblRolesSuccess.Text = "<ul><li>" & GetString("UserAddedToRole", LocalResourceFile) & "</li></ul>"
                Me.pnlRolesSuccess.Visible = True
                Me.pnlRolesIntro.Visible = False
                Me.pnlRolesError.Visible = False

            End If

        End Sub

        Protected Sub btnNotifyRole_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnNotifyRole.Click


            Dim strPassword As String = MembershipProvider.Instance().GetPassword(User, "")
            Dim strBody As String = txtNotifyRoleBody.Content.Replace(GetString("HiddenPassword", LocalResourceFile), strPassword)
            Dim strSubject As String = txtNotifyRoleSubject.Text
            If strSubject = "" Then
                strSubject = txtNotifyRoleSubject.EmptyMessage.Replace(GetString("SubjectPrefix", LocalResourceFile), "")
            End If

            Mail.SendEmail(PortalSettings.Email, User.Email, strSubject, strBody)

            Dim cmdReason As String = CType(sender, Button).CommandArgument
            Select Case cmdReason.ToLower
                Case "remove"
                    Me.lblRolesSuccess.Text = "<ul><li>" & GetString("UserNotifiedRemoval", LocalResourceFile) & "</li></ul>"
                Case "add"
                    Me.lblRolesSuccess.Text = "<ul><li>" & GetString("UserNotifiedAddedToRole", LocalResourceFile) & "</li></ul>"
            End Select

            Me.pnlRolesSuccess.Visible = True
            Me.pnlRolesIntro.Visible = False
            Me.pnlRolesError.Visible = False

            pnlRoleChange_Step1.Visible = True
            pnlRoleChange_Step2.Visible = False
            ctlRoleDateTo.Clear()
            ctlRoleDatFrom.Clear()
            drpRoles.SelectedIndex = 0
            lblRolesIntro.Text = GetString("SecurityRoles", LocalResourceFile)
            grdUserRoles.Rebind()

        End Sub

        Protected Sub btnNotifyRoleSkip_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnNotifyRoleSkip.Click

            pnlRoleChange_Step1.Visible = True
            pnlRoleChange_Step2.Visible = False
            ctlRoleDateTo.Clear()
            ctlRoleDatFrom.Clear()
            drpRoles.SelectedIndex = 0
            lblRolesIntro.Text = GetString("SecurityRoles", LocalResourceFile)
            grdUserRoles.Rebind()

            Me.pnlRolesSuccess.Visible = False
            Me.pnlRolesIntro.Visible = True
            Me.pnlRolesError.Visible = False

        End Sub

        Protected Sub btnDeleteAccount_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDeleteAccount.Click

            Dim intUser As Integer = User.UserID
            Dim oUser As UserInfo = User

            UserController.DeleteUser(oUser, False, False)

            Dim intRole As Integer = Null.NullInteger

            If IsNumeric(ctlRoles.SelectedNode.Value) Then
                Dim roleid As Integer = Convert.ToInt32(ctlRoles.SelectedNode.Value)
                intRole = roleid
            End If

            If intRole <> Null.NullInteger Then
                Response.Redirect(NavigateURL(TabId, "", "RoleId=" & intRole.ToString))
            Else
                Response.Redirect(NavigateURL(TabId, ""))
            End If

        End Sub

        Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click

            If txtSearch.Text.Length > 0 Then

                Session("dnnWerk_UserSearchTerm") = txtSearch.Text

                SaveSearchOptions()
                pnlGrid.Visible = True
                pnlUser.Visible = False
                pnlCreate.Visible = False
                grdUsers.Rebind()



            End If

        End Sub

        Protected Sub btnApplyOptions_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnApplyOptions.Click
            SaveGridOptions()
            SaveSearchOptions()
            If Not Request.QueryString("RoleId") Is Nothing Then
                Response.Redirect(NavigateURL(TabId, "", "RoleId=" & Request.QueryString("RoleId")))
            Else
                Response.Redirect(NavigateURL(TabId))
            End If
        End Sub

        Protected Sub btnRunReport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRunReport.Click

            _IsReportResult = True

            If drpReports.SelectedIndex > 0 Then
                ctlRoles.UnselectAllNodes()
                grdUsers.Rebind()
            End If

            pnlGrid.Visible = True
            pnlUser.Visible = False
            pnlCreate.Visible = False

        End Sub

#End Region

#Region "Private Methods"

        Private Sub InitializeForm()


            Dim strTemplatePath As String = Me.ModuleDirectory & "/Editor"
            If Not System.IO.Directory.Exists(Server.MapPath(strTemplatePath)) Then
                System.IO.Directory.CreateDirectory(Server.MapPath(strTemplatePath))
            End If
            strTemplatePath += "/Portals"
            If Not System.IO.Directory.Exists(Server.MapPath(strTemplatePath)) Then
                System.IO.Directory.CreateDirectory(Server.MapPath(strTemplatePath))
            End If
            strTemplatePath += "/" & PortalId.ToString
            If Not System.IO.Directory.Exists(Server.MapPath(strTemplatePath)) Then
                System.IO.Directory.CreateDirectory(Server.MapPath(strTemplatePath))
            End If

            For Each file As String In System.IO.Directory.GetFiles(Server.MapPath(Me.ModuleDirectory & "/Templates/ManageUsers/" & ModuleId.ToString))
                Dim strFilename As String = file.Substring(file.LastIndexOf("\") + 1)
                If strFilename.ToLower.StartsWith("email") Then
                    Dim strTargetFilename As String = Server.MapPath(strTemplatePath & "/" & strFilename.Replace("txt", "html"))
                    If System.IO.File.Exists(strTargetFilename) = False Then
                        System.IO.File.Copy(file, strTargetFilename)
                    End If
                End If
            Next

            Me.txtNotifyPasswordBody.TemplateManager.ViewPaths = New String() {strTemplatePath}
            Me.txtNotifyPasswordBody.TemplateManager.UploadPaths = New String() {strTemplatePath}
            Me.txtNotifyPasswordBody.TemplateManager.DeletePaths = New String() {strTemplatePath}

            Me.txtNotifyRoleBody.TemplateManager.ViewPaths = New String() {strTemplatePath}
            Me.txtNotifyRoleBody.TemplateManager.UploadPaths = New String() {strTemplatePath}
            Me.txtNotifyRoleBody.TemplateManager.DeletePaths = New String() {strTemplatePath}

            Me.txtUserCreatedBody.TemplateManager.ViewPaths = New String() {strTemplatePath}
            Me.txtUserCreatedBody.TemplateManager.UploadPaths = New String() {strTemplatePath}
            Me.txtUserCreatedBody.TemplateManager.DeletePaths = New String() {strTemplatePath}

            Me.txtEmailUserBody.TemplateManager.ViewPaths = New String() {strTemplatePath}
            Me.txtEmailUserBody.TemplateManager.UploadPaths = New String() {strTemplatePath}
            Me.txtEmailUserBody.TemplateManager.DeletePaths = New String() {strTemplatePath}


            'btnActionContainer.Visible = AllowCreate
            If AllowCreate Then
                btnAction.Enabled = True
                btnAction.CommandName = "Create"
                btnAction.Text = GetString("CreateUser", LocalResourceFile)
            Else
                btnAction.CommandName = ""
                btnAction.Text = ""
                btnAction.Enabled = False
            End If

            btnExportContainer.Visible = AllowExport
            btnExport.Visible = AllowExport
            btnExport.Text = GetString("Export", LocalResourceFile)

            btnHardDelete.Text = GetString("HardDeleteAll", LocalResourceFile)

            Me.ctlRoleDateTo.DateInput.EmptyMessage = GetString("EffectiveDate", LocalResourceFile)
            Me.ctlRoleDatFrom.DateInput.EmptyMessage = GetString("ExpiryDate", LocalResourceFile)

            Me.txtUserCreatedBody.ToolsFile = Me.TemplateSourceDirectory & "/Config/Toolsfile.xml"
            Me.txtUserCreatedBody.DialogHandlerUrl = Me.Page.ResolveUrl(Me.ModuleDirectory & "/DialogHandler.aspx?tabid=" & PortalSettings.ActiveTab.TabID.ToString())
            Me.txtUserCreatedSubject.EmptyMessage = GetString("SubjectPrefix", LocalResourceFile) & String.Format(GetString("SubjectAccountDetails", LocalResourceFile), PortalSettings.PortalName)

            Me.txtNotifyRoleBody.ToolsFile = Me.TemplateSourceDirectory & "/Config/Toolsfile.xml"
            Me.txtNotifyRoleBody.DialogHandlerUrl = Me.Page.ResolveUrl(Me.ModuleDirectory & "/DialogHandler.aspx?tabid=" & PortalSettings.ActiveTab.TabID.ToString())
            Me.txtNotifyRoleSubject.EmptyMessage = GetString("SubjectPrefix", LocalResourceFile) & String.Format(GetString("SubjectRoleMembershipChanged", LocalResourceFile), PortalSettings.PortalName)

            Me.txtNotifyPasswordBody.ToolsFile = Me.TemplateSourceDirectory & "/Config/Toolsfile.xml"
            Me.txtNotifyPasswordBody.DialogHandlerUrl = Me.Page.ResolveUrl(Me.ModuleDirectory & "/DialogHandler.aspx?tabid=" & PortalSettings.ActiveTab.TabID.ToString())
            Me.txtNotifyPasswordSubject.EmptyMessage = GetString("SubjectPrefix", LocalResourceFile) & String.Format(GetString("SubjectPasswordRequested", LocalResourceFile), PortalSettings.PortalName)

            Me.txtEmailUserBody.ToolsFile = Me.TemplateSourceDirectory & "/Config/Toolsfile.xml"
            Me.txtEmailUserBody.DialogHandlerUrl = Me.Page.ResolveUrl(Me.ModuleDirectory & "/DialogHandler.aspx?tabid=" & PortalSettings.ActiveTab.TabID.ToString())
            Me.txtEmailUserSubject.EmptyMessage = GetString("SubjectPrefix", LocalResourceFile) & String.Format(GetString("SubjectAccountDetails", LocalResourceFile), PortalSettings.PortalName)



            btnCreateUser.Text = GetString("CreateUser", LocalResourceFile)
            ctlSearchTabs.Tabs(0).Text = GetString("SearchTab", LocalResourceFile)
            ctlSearchTabs.Tabs(1).Text = GetString("OptionsTab", LocalResourceFile)
            btnSearch.Text = GetString("btnSearch", LocalResourceFile)
            txtSearch.EmptyMessage = GetString("SearchUsers", LocalResourceFile)
            btnApplyOptions.Text = GetString("ApplyOptions", LocalResourceFile)
            lblSearchOptions.Text = GetString("SearchOptions", LocalResourceFile)
            lblPageSize.Text = GetString("PageSize", LocalResourceFile)
            lblGridSetup.Text = GetString("GridSetup", LocalResourceFile)
            drpPageSize.Items(4).Text = GetString("All", LocalResourceFile)

            For Each item As ListItem In chkGridOptions.Items

                Dim strText As String = ""
                strText = GetString("ProfileProperties_" & item.Value & ".Text", ProfileResourcefile)

                If strText = "" OrElse strText.StartsWith("RESX:") Then
                    item.Text = GetString(item.Value, LocalResourceFile)
                Else
                    item.Text = strText.Replace(":", "")
                End If

            Next

            For Each col As GridColumn In grdUsers.Columns
                If col.UniqueName.Length > 0 Then
                    col.HeaderText = GetString(col.UniqueName.Replace("col_", ""), LocalResourceFile)
                End If
            Next

            ctlFilterTabs.Tabs(0).Text = GetString("rolesTab", LocalResourceFile)
            ctlFilterTabs.Tabs(1).Text = GetString("ReportsTab", LocalResourceFile)
            btnRunReport.Text = GetString("RunReport", LocalResourceFile)

            lblAccountIntro.Text = GetString("AccountIntro", LocalResourceFile)
            btnDeleteAccount.Text = GetString("btnDeleteAccount", LocalResourceFile)
            btnUpdateAccount.Text = GetString("btnUpdateAccount", LocalResourceFile)
            lblMembershipIntro.Text = GetString("MembershipIntro", LocalResourceFile)
            lblMemberSinceLabel.Text = GetString("MemberSinceLabel", LocalResourceFile)
            lblLastLoginLabel.Text = GetString("LastLoginLabel", LocalResourceFile)
            lblLastActivityLabel.Text = GetString("LastActivityLabel", LocalResourceFile)
            lblLastPasswordChangeLabel.Text = GetString("LastPasswordChangeLabel", LocalResourceFile)
            lblLastLockoutLabel.Text = GetString("LastLockoutLabel", LocalResourceFile)
            btnUnlockAccount.Text = GetString("btnUnlockAccount", LocalResourceFile)
            btnAuthorize.Text = GetString("btnAuthorize", LocalResourceFile)
            btnForcePasswordChange.Text = GetString("btnForcePasswordChange", LocalResourceFile)

            lblProfileIntro.Text = GetString("ProfileIntro", LocalResourceFile)
            btnUpdateProfile.Text = GetString("btnUpdateProfile", LocalResourceFile)

            lblPasswordIntro.Text = GetString("PasswordIntro", LocalResourceFile)
            lblNewPassword1.Text = GetString("NewPassword1", LocalResourceFile)
            lblNewPassword2.Text = GetString("NewPassword2", LocalResourceFile)
            chkAutoGeneratePassword.Text = GetString("AutoGeneratePassword", LocalResourceFile)
            lblGeneratePasswordNote.Text = GetString("GeneratePasswordNote", LocalResourceFile)
            btnUpdatePassword.Text = GetString("btnUpdatePassword", LocalResourceFile)
            btnNotifyPassword.Text = GetString("btnNotifyPassword", LocalResourceFile)
            btnNotifyPasswordSkip.Text = GetString("btnNotifyPasswordSkip", LocalResourceFile)

            lblRolesIntro.Text = GetString("RolesIntro", LocalResourceFile)
            btnAddToRole.Text = GetString("btnAddToRole", LocalResourceFile)

            For Each col As GridColumn In grdUserRoles.Columns
                If col.UniqueName.Length > 0 Then
                    col.HeaderText = GetString(col.UniqueName.Replace("col_", ""), LocalResourceFile)
                End If
            Next
            btnNotifyRole.Text = GetString("btnNotifyRole", LocalResourceFile)
            btnNotifyRoleSkip.Text = GetString("btnNotifyRoleSkip", LocalResourceFile)

            lblEmailIntro.Text = GetString("EmailIntro", LocalResourceFile)
            btnSendEmail.Text = GetString("btnSendEmail", LocalResourceFile)

            lblCreateUserIntro.Text = GetString("CreateUserIntro", LocalResourceFile)
            btnCreateUser.Text = GetString("btnCreateUser", LocalResourceFile)
            btnNotifyCreateUser.Text = GetString("btnNotifyCreateUser", LocalResourceFile)
            btnNotifyCreateUserSkip.Text = GetString("btnNotifyCreateUserSkip", LocalResourceFile)

            lblPasswordNotificationNote_Create.Text = String.Format(GetString("PasswordNotificationNote", LocalResourceFile), GetString("HiddenPassword", LocalResourceFile))
            lblPasswordNotificationNote_Email.Text = String.Format(GetString("PasswordNotificationNote", LocalResourceFile), GetString("HiddenPassword", LocalResourceFile))
            lblPasswordNotificationNote_Password.Text = String.Format(GetString("PasswordNotificationNote", LocalResourceFile), GetString("HiddenPassword", LocalResourceFile))
            lblPasswordNotificationNote_Roles.Text = String.Format(GetString("PasswordNotificationNote", LocalResourceFile), GetString("HiddenPassword", LocalResourceFile))

        End Sub

        Private Sub BindSearchColOptions()

            chkSearchCols.Items.Clear()

            chkSearchCols.Items.Add(New ListItem("Username", "Username"))
            chkSearchCols.Items.Add(New ListItem("DisplayName", "DisplayName"))
            chkSearchCols.Items.Add(New ListItem("Email", "Email"))


            Dim props As ProfilePropertyDefinitionCollection = ProfileController.GetPropertyDefinitionsByPortal(PortalSettings.PortalId)
            For Each prop As ProfilePropertyDefinition In props
                Try
                    chkSearchCols.Items.Add(New ListItem(LocalizeProperty(prop).Replace(":", ""), prop.PropertyName))
                Catch ex As Exception
                    chkSearchCols.Items.Add(New ListItem(prop.PropertyName, prop.PropertyName))
                End Try

            Next

        End Sub

        Private Sub PersonalizeOptions()

            For Each item As ListItem In chkSearchCols.Items
                item.Selected = False
            Next

            For Each item As ListItem In chkGridOptions.Items
                item.Selected = False
            Next

            Dim strSearchCols As String = "FirstName,LastName,City,Email,"
            Dim searchcols As Object = DotNetNuke.Services.Personalization.Personalization.GetProfile("dnnWerk_Users_ColOptions", "SearchCols_" & UserId.ToString)
            If Not searchcols Is Nothing Then
                If searchcols.ToString.Length > 0 Then
                    strSearchCols = searchcols.ToString
                End If
            End If

            For Each strSearchCol As String In strSearchCols.Split(Char.Parse(","))
                If strSearchCol.Length > 0 Then
                    For Each item As ListItem In chkSearchCols.Items
                        If item.Value.ToLower = strSearchCol.ToLower Then
                            item.Selected = True
                        End If
                    Next
                End If
            Next

            Dim strGridCols As String = "DisplayName,Username,Email,Country,CreatedDate,"
            Dim gridcols As Object = DotNetNuke.Services.Personalization.Personalization.GetProfile("dnnWerk_Users_ColOptions", "GridCols_" & UserId.ToString)
            If Not gridcols Is Nothing Then
                If gridcols.ToString.Length > 0 Then
                    strGridCols = gridcols.ToString
                End If
            End If

            For Each strGridCol As String In strGridCols.Split(Char.Parse(","))
                If strGridCol.Length > 0 Then
                    For Each item As ListItem In chkGridOptions.Items
                        If item.Value.ToLower = strGridCol.ToLower Then
                            item.Selected = True
                        End If
                    Next
                End If
            Next

            Dim pagesize As String = "25"
            Try
                pagesize = DotNetNuke.Services.Personalization.Personalization.GetProfile("dnnWerk_Users_ColOptions", "GridPageSize_" & UserId.ToString)
            Catch
            End Try
            Try
                drpPageSize.Items.FindItemByText(pagesize.ToString).Selected = True
            Catch
            End Try

            'set up grid
            For Each strGridCol As String In strGridCols.Split(Char.Parse(","))
                If strGridCol.ToString.Length > 0 Then

                    Dim strCol As String = "col_" & strGridCol
                    Try
                        grdUsers.Columns.FindByUniqueName(strCol).Visible = True
                    Catch
                    End Try

                End If
            Next

            If drpPageSize.SelectedItem.Value = "All" Then
                grdUsers.AllowPaging = False
            Else
                grdUsers.AllowPaging = True
                grdUsers.PageSize = Convert.ToInt32(drpPageSize.SelectedItem.Value)
            End If

        End Sub

        Private Sub SaveSearchOptions()

            Dim strCols As String = ""
            For Each item As ListItem In chkSearchCols.Items
                If item.Selected = True Then
                    strCols += item.Value & ","
                End If
            Next

            DotNetNuke.Services.Personalization.Personalization.SetProfile("dnnWerk_Users_ColOptions", "SearchCols_" & UserId.ToString, strCols)

        End Sub

        Private Sub SaveGridOptions()

            Dim strCols As String = ""
            For Each item As ListItem In chkGridOptions.Items
                If item.Selected = True Then
                    strCols += item.Value & ","
                End If
            Next

            DotNetNuke.Services.Personalization.Personalization.SetProfile("dnnWerk_Users_ColOptions", "GridCols_" & UserId.ToString, strCols)

            DotNetNuke.Services.Personalization.Personalization.SetProfile("dnnWerk_Users_ColOptions", "GridPageSize_" & UserId.ToString, drpPageSize.SelectedItem.Value)

        End Sub

        Private Sub LoadAdditionalControls()

            If AdditionalControls.Length > 0 Then

                Dim strTabname As String = ""
                Dim strControl As String = ""

                For Each objControl As String In AdditionalControls

                    Try
                        strTabname = objControl.Split(Char.Parse(","))(0)
                        strControl = objControl.Split(Char.Parse(","))(1)
                    Catch
                    End Try

                    If strTabname.Length > 0 AndAlso strControl.Length > 0 Then

                        Dim relUrl As String = ResolveUrl("~" & strControl)
                        Dim path As String = Server.MapPath(relUrl)
                        If System.IO.File.Exists(path) AndAlso path.EndsWith(".ascx") Then

                            'ok, we've got a tabname and a valid control to load
                            Dim objModule As PortalModuleBase = CType(Me.LoadControl(relUrl), PortalModuleBase)
                            objModule.ModuleConfiguration = Me.ModuleConfiguration
                            objModule.ID = System.IO.Path.GetFileNameWithoutExtension(relUrl)

                            Dim objTab As New RadTab(strTabname)
                            objTab.PageViewID = "pva_" & objModule.ID
                            ctlTabs.Tabs.Add(objTab)

                            Dim objPageView As New RadPageView()
                            objPageView.ID = "pva_" & objModule.ID
                            objPageView.CssClass = "ucPv"
                            ctlTabPages.PageViews.Add(objPageView)

                            objPageView.Controls.Add(objModule)

                        End If

                    End If

                Next
            End If

        End Sub

        Private Sub BindRoles()

            Dim objRoleController As New RoleController

            Dim roles As ArrayList = objRoleController.GetPortalRoles(PortalId)
            Dim groups As ArrayList = RoleController.GetRoleGroups(PortalId)

            If groups.Count > 0 Then
                'we have some role groups, add those first
                For Each objGroup As RoleGroupInfo In groups

                    Dim groupnode As New RadTreeNode(objGroup.RoleGroupName, -1)
                    groupnode.Attributes.Add("IsGroup", True)
                    groupnode.ImageUrl = Me.TemplateSourceDirectory & "/images/folder.png"
                    groupnode.PostBack = False

                    Dim groupItem As New RadComboBoxItem
                    groupItem.Text = objGroup.RoleGroupName
                    groupItem.Value = "-1"
                    groupItem.ImageUrl = Me.TemplateSourceDirectory & "/images/folder.png"
                    groupItem.Attributes.Add("IsGroup", True)
                    groupItem.IsSeparator = True

                    drpRoles.Items.Add(groupItem)

                    For Each objRole As RoleInfo In roles
                        If objRole.RoleGroupID = objGroup.RoleGroupID Then

                            If Not BrowseRoles Is Nothing AndAlso Array.IndexOf(BrowseRoles, objRole.RoleID.ToString) > -1 Then

                                Dim rolenode As New RadTreeNode(objRole.RoleName, objRole.RoleID.ToString)
                                rolenode.ImageUrl = Me.TemplateSourceDirectory & "/images/users.png"
                                rolenode.Attributes.Add("IsGroup", False)
                                If Not Request.QueryString("uid") Is Nothing Then
                                    rolenode.PostBack = False
                                    If Not Request.QueryString("uid") Is Nothing Then
                                        rolenode.NavigateUrl = NavigateURL(TabId, "", "RoleId=" & objRole.RoleID.ToString)
                                    Else
                                        rolenode.NavigateUrl = NavigateURL(TabId)
                                    End If
                                End If

                                groupnode.Nodes.Add(rolenode)

                                Dim roleItem As New RadComboBoxItem
                                roleItem.Text = objRole.RoleName
                                roleItem.Value = objRole.RoleID
                                roleItem.ImageUrl = Me.TemplateSourceDirectory & "/images/users.png"
                                roleItem.Attributes.Add("style", "margin-left: 20px;")
                                drpRoles.Items.Add(roleItem)

                            End If

                        End If

                    Next

                    If groupnode.Nodes.Count > 0 Then
                        ctlRoles.Nodes.Add(groupnode)
                    End If


                Next

                For Each objRole As RoleInfo In roles
                    If objRole.RoleGroupID = Null.NullInteger Then

                        If Not BrowseRoles Is Nothing AndAlso Array.IndexOf(BrowseRoles, objRole.RoleID.ToString) > -1 Then

                            Dim rolenode As New RadTreeNode(objRole.RoleName, objRole.RoleID.ToString)
                            rolenode.Attributes.Add("IsGroup", False)
                            rolenode.ImageUrl = Me.TemplateSourceDirectory & "/images/users.png"
                            If Not Request.QueryString("uid") Is Nothing Then
                                rolenode.PostBack = False
                                If Not Request.QueryString("uid") Is Nothing Then
                                    rolenode.NavigateUrl = NavigateURL(TabId, "", "RoleId=" & objRole.RoleID.ToString)
                                Else
                                    rolenode.NavigateUrl = NavigateURL(TabId)
                                End If
                            End If

                            ctlRoles.Nodes.Add(rolenode)

                            If objRole.RoleID <> PortalSettings.RegisteredRoleId Then
                                Dim roleItem As New RadComboBoxItem
                                roleItem.Text = objRole.RoleName
                                roleItem.Value = objRole.RoleID
                                roleItem.ImageUrl = Me.TemplateSourceDirectory & "/images/users.png"
                                drpRoles.Items.Add(roleItem)
                            End If

                        End If


                    End If

                Next
            Else
                For Each objRole As RoleInfo In roles

                    If Not BrowseRoles Is Nothing AndAlso Array.IndexOf(BrowseRoles, objRole.RoleID.ToString) > -1 Then

                        Dim rolenode As New RadTreeNode(objRole.RoleName, objRole.RoleID.ToString)
                        rolenode.ImageUrl = Me.TemplateSourceDirectory & "/images/users.png"
                        rolenode.Attributes.Add("IsGroup", False)
                        If Not Request.QueryString("uid") Is Nothing Then
                            rolenode.PostBack = False
                            If Not Request.QueryString("uid") Is Nothing Then
                                rolenode.NavigateUrl = NavigateURL(TabId, "", "RoleId=" & objRole.RoleID.ToString)
                            Else
                                rolenode.NavigateUrl = NavigateURL(TabId)
                            End If
                        End If
                        ctlRoles.Nodes.Add(rolenode)

                        If objRole.RoleID <> PortalSettings.RegisteredRoleId Then
                            Dim roleItem As New RadComboBoxItem
                            roleItem.Text = objRole.RoleName
                            roleItem.Value = objRole.RoleID
                            roleItem.ImageUrl = Me.TemplateSourceDirectory & "/images/users.png"
                            drpRoles.Items.Add(roleItem)
                        End If

                    End If


                Next
            End If

            If Not BrowseRoles Is Nothing AndAlso Array.IndexOf(BrowseRoles, "-2") > -1 Then
                Dim binnode As New RadTreeNode("Deleted Users", "-2")
                binnode.ImageUrl = "~/images/action_delete.gif"
                binnode.Attributes.Add("IsGroup", False)
                If Not Request.QueryString("uid") Is Nothing Then
                    binnode.PostBack = False
                    If Not Request.QueryString("uid") Is Nothing Then
                        binnode.NavigateUrl = NavigateURL(TabId, "", "RoleId=-2")
                    Else
                        binnode.NavigateUrl = NavigateURL(TabId)
                    End If
                End If
                ctlRoles.Nodes.Add(binnode)
            End If


            Dim SelectedRole As String = ""
            If Not Request.QueryString("RoleId") Is Nothing Then
                SelectedRole = Request.QueryString("RoleId")
            Else
                If Me.PreSelectRole <> Null.NullInteger Then
                    SelectedRole = Me.PreSelectRole.ToString
                Else
                    SelectedRole = PortalSettings.RegisteredRoleId.ToString
                End If

            End If

            Try
                ctlRoles.UnselectAllNodes()
                ctlRoles.FindNodeByValue(SelectedRole).Selected = True
                ctlRoles.FindNodeByValue(SelectedRole).ExpandParentNodes()
            Catch
            End Try

        End Sub

        Private Sub BindUserTabs()

            If ShowUserDetailTabs.Length > 0 Then

                ctlTabs.Tabs.Clear()

                For Each strTab As String In ShowUserDetailTabs
                    If strTab.Length > 0 Then

                        Dim oTab As New RadTab
                        oTab.Text = GetString(strTab.ToLower & "Tab", LocalResourceFile)
                        oTab.Value = strTab.ToLower
                        oTab.PageViewID = strTab.ToLower & "Tab"
                        ctlTabs.Tabs.Add(oTab)

                    End If
                Next

            Else

                For Each oTab As RadTab In ctlTabs.Tabs
                    oTab.Text = GetString(oTab.Value & "Tab", LocalResourceFile)
                Next

            End If

            ctlTabPages.FindPageViewByID(ctlTabs.Tabs(0).PageViewID).Selected = True

        End Sub

        Private Sub BindUsers()

            If ctlRoles.SelectedNode Is Nothing Then
                _IsReportResult = Page.IsPostBack
            Else
                _IsReportResult = False
            End If

            If _IsReportResult Then

                Dim strError As String = ""
                grdUsers.DataSource = GetReportResult(strError)

                If strError.Length > 0 Then
                    grdUsers.MasterTableView.NoMasterRecordsText = "<p style='padding:10px;'>" & strError & "</p>"
                Else
                    grdUsers.MasterTableView.NoMasterRecordsText = "<p style='padding:10px;'>The report does not return any data.</p>"
                End If

            Else

                If Not Session("dnnWerk_UserSearchTerm") Is Nothing Then
                    txtSearch.Text = CType(Session("dnnWerk_UserSearchTerm"), String)
                End If

                If txtSearch.Text.Length = 0 Then
                    grdUsers.MasterTableView.NoMasterRecordsText = "<p style='padding:10px;'>No users found in the selected role</p>"
                Else
                    grdUsers.MasterTableView.NoMasterRecordsText = "<p style='padding:10px;'>Your search does not contain any results!</p>"
                End If

                grdUsers.DataSource = GetUserList()

            End If


        End Sub

        Private Sub BindUser(ByVal UserId As Integer)


            btnDeleteAccount.Visible = (UserId <> PortalSettings.AdministratorId AndAlso AllowDelete)

            btnAction.CommandName = "back"
            btnAction.Text = GetString("Back", LocalResourceFile)
            btnAction.Enabled = True

            pnlGrid.Visible = False
            pnlCreate.Visible = False
            pnlUser.Visible = True

            Dim objController As New UserController
            Dim objUser As UserInfo = objController.GetUser(PortalId, UserId)

            ProcessFormTemplate(plhUser, Template_EditAccount(CurrentLocale), objUser, _PageNeedsToPostback)
            ProcessFormTemplate(plhProfile, Template_EditProfile(CurrentLocale), objUser, _PageNeedsToPostback)


            If User.Membership.IsOnLine Then
                imgOnlineStatus.ImageUrl = Me.ResolveUrl("~/images/green-ok.gif")
                lblOnlineStatus.Text = GetString("UserIsOnline", LocalResourceFile)
            Else
                imgOnlineStatus.ImageUrl = Me.ResolveUrl("~/images/icon_hostusers_32px.gif")
                lblOnlineStatus.Text = GetString("UserIsOffline", LocalResourceFile)
            End If

            If User.Membership.Approved Then
                imgAuthorizedStatus.ImageUrl = Me.ResolveUrl("~/images/green-ok.gif")
                lblAuthorizedStatus.Text = GetString("UserIsAuthorized", LocalResourceFile)
            Else
                imgAuthorizedStatus.ImageUrl = Me.ResolveUrl("~/images/yellow-warning.gif")
                lblAuthorizedStatus.Text = GetString("UserIsAwaitingApproval", LocalResourceFile)
            End If

            If User.Membership.UpdatePassword Then
                btnForcePasswordChange.Visible = False
                pnlForcePasswordChange.Visible = True
                imgForcePasswordChange.ImageUrl = Me.ResolveUrl("~/images/yellow-warning.gif")
                lblForcePasswordChange.Text = GetString("UserIsForcedToPasswordChange", LocalResourceFile)
            Else
                btnForcePasswordChange.Visible = True
                pnlForcePasswordChange.Visible = False
            End If


            btnAuthorize.Visible = (User.Membership.Approved = False)

            If User.Membership.LockedOut Then
                pnlLockedOut.Visible = True
                imgLockedOut.ImageUrl = Me.ResolveUrl("~/images/yellow-warning.gif")
                lblLockedOut.Text = GetString("UserIsLockedOut", LocalResourceFile)
                btnUnlockAccount.Visible = True
            Else
                pnlLockedOut.Visible = False
                btnUnlockAccount.Visible = False
            End If

            lblMemberSince.Text = User.Membership.CreatedDate.ToShortDateString & ", " & User.Membership.CreatedDate.ToShortTimeString
            lblLastActivity.Text = User.Membership.LastActivityDate.ToShortDateString & ", " & User.Membership.LastActivityDate.ToShortTimeString
            lblLastLockOut.Text = User.Membership.LastLockoutDate.ToShortDateString & ", " & User.Membership.LastLockoutDate.ToShortTimeString
            lblLastLogin.Text = User.Membership.LastLoginDate.ToShortDateString & ", " & User.Membership.LastLoginDate.ToShortTimeString

            If lblLastActivity.Text = "" Then
                lblLastActivity.Text = GetString("Never", LocalResourceFile)
            End If

            If lblLastLockOut.Text = "" Then
                lblLastLockOut.Text = GetString("Never", LocalResourceFile)
            End If

            If lblLastLogin.Text = "" Then
                lblLastLogin.Text = GetString("Never", LocalResourceFile)
            End If

            If lblLastPasswordChange.Text = "" Then
                lblLastPasswordChange.Text = GetString("Never", LocalResourceFile)
            End If

            'Bind e-mail editor
            BindUserNotification()

            If Not Request.QueryString("Restored") Is Nothing Then
                If Boolean.Parse(Request.QueryString("Restored")) = True Then
                    pnlAccountSuccess.Visible = True
                    pnlAccountIntro.Visible = False
                    pnlAccountError.Visible = False
                    lblAccountSuccess.Text = "<ul><li>" & GetString("AccountRestored", LocalResourceFile) & "</li></ul>"
                End If
            End If

        End Sub

        Private Sub ResetPassword(ByVal AutoGenerate As Boolean)

            Dim strMessage As String = ""
            Dim strPassword As String = ""

            If AutoGenerate = False Then
                strPassword = txtPassword1.Text
            Else
                strPassword = UserController.GeneratePassword(7)
            End If

            UserController.ChangePassword(User, "", strPassword)

            Me.pnlPasswordSuccess.Visible = True
            Me.lblPasswordSucess.Text = "<ul><li>" & GetString("PasswordUpdated", LocalResourceFile) & "</li></ul>"


            Me.lblPasswordSucess.Text += "</ul>"
            Me.pnlPasswordSuccess.Visible = True
            Me.pnlPasswordError.Visible = False



        End Sub

        Private Sub BindPasswordNotification()

            Dim strTemplate As String = Template_EmailPasswordReset(User.Profile.PreferredLocale)

            strTemplate = strTemplate.Replace("[FIRSTNAME]", User.FirstName)
            strTemplate = strTemplate.Replace("[LASTNAME]", User.LastName)
            strTemplate = strTemplate.Replace("[DISPLAYNAME]", User.DisplayName)
            strTemplate = strTemplate.Replace("[PORTALNAME]", PortalSettings.PortalName)
            strTemplate = strTemplate.Replace("[PORTALURL]", PortalSettings.PortalAlias.HTTPAlias)
            strTemplate = strTemplate.Replace("[USERNAME]", User.Username)
            strTemplate = strTemplate.Replace("[PASSWORD]", GetString("HiddenPassword", LocalResourceFile))

            txtNotifyPasswordBody.Content = strTemplate

        End Sub

        Private Sub BindUserCreateNotification(ByVal objUser As UserInfo)

            Dim strTemplate As String = Template_EmailAccountCreated(objUser.Profile.PreferredLocale)

            strTemplate = strTemplate.Replace("[FIRSTNAME]", objUser.FirstName)
            strTemplate = strTemplate.Replace("[LASTNAME]", objUser.LastName)
            strTemplate = strTemplate.Replace("[DISPLAYNAME]", objUser.DisplayName)
            strTemplate = strTemplate.Replace("[PORTALNAME]", PortalSettings.PortalName)
            strTemplate = strTemplate.Replace("[PORTALURL]", PortalSettings.PortalAlias.HTTPAlias)
            strTemplate = strTemplate.Replace("[USERNAME]", objUser.Username)
            strTemplate = strTemplate.Replace("[PASSWORD]", GetString("HiddenPassword", LocalResourceFile))

            txtUserCreatedBody.Content = strTemplate

        End Sub

        Private Sub BindUserNotification()

            Dim strTemplate As String = Template_EmailAccountData(User.Profile.PreferredLocale)

            strTemplate = strTemplate.Replace("[FIRSTNAME]", User.FirstName)
            strTemplate = strTemplate.Replace("[LASTNAME]", User.LastName)
            strTemplate = strTemplate.Replace("[DISPLAYNAME]", User.DisplayName)
            strTemplate = strTemplate.Replace("[PORTALNAME]", PortalSettings.PortalName)
            strTemplate = strTemplate.Replace("[PORTALURL]", PortalSettings.PortalAlias.HTTPAlias)
            strTemplate = strTemplate.Replace("[USERNAME]", User.Username)
            strTemplate = strTemplate.Replace("[PASSWORD]", GetString("HiddenPassword", LocalResourceFile))

            txtEmailUserBody.Content = strTemplate

        End Sub

        Private Sub BindRoleRemoveNotification(ByVal strRole As String)

            Dim strTemplate As String = Template_EmailRemovedFromRole(User.Profile.PreferredLocale)

            strTemplate = strTemplate.Replace("[FIRSTNAME]", User.FirstName)
            strTemplate = strTemplate.Replace("[LASTNAME]", User.LastName)
            strTemplate = strTemplate.Replace("[DISPLAYNAME]", User.DisplayName)
            strTemplate = strTemplate.Replace("[PORTALNAME]", PortalSettings.PortalName)
            strTemplate = strTemplate.Replace("[PORTALURL]", PortalSettings.PortalAlias.HTTPAlias)
            strTemplate = strTemplate.Replace("[USERNAME]", User.Username)
            strTemplate = strTemplate.Replace("[PASSWORD]", GetString("HiddenPassword", LocalResourceFile))
            strTemplate = strTemplate.Replace("[ROLE]", strRole)

            txtNotifyRoleBody.Content = strTemplate

        End Sub

        Private Sub BindRoleAddNotification(ByVal strRole As String, ByVal EffectiveDate As Date, ByVal ExpiryDate As Date)

            Dim strTemplate As String = Template_EmailAddedToRole(User.Profile.PreferredLocale)

            strTemplate = strTemplate.Replace("[FIRSTNAME]", User.FirstName)
            strTemplate = strTemplate.Replace("[LASTNAME]", User.LastName)
            strTemplate = strTemplate.Replace("[DISPLAYNAME]", User.DisplayName)
            strTemplate = strTemplate.Replace("[PORTALNAME]", PortalSettings.PortalName)
            strTemplate = strTemplate.Replace("[PORTALURL]", PortalSettings.PortalAlias.HTTPAlias)
            strTemplate = strTemplate.Replace("[USERNAME]", User.Username)
            strTemplate = strTemplate.Replace("[PASSWORD]", GetString("HiddenPassword", LocalResourceFile))
            strTemplate = strTemplate.Replace("[ROLE]", strRole)

            If EffectiveDate <> Null.NullDate Then
                strTemplate = strTemplate.Replace("[EFFECTIVEDATE]", EffectiveDate.ToShortDateString)
            Else
                strTemplate = strTemplate.Replace("[EFFECTIVEDATE]", Date.Now.ToShortDateString)
            End If

            If ExpiryDate <> Null.NullDate Then
                strTemplate = strTemplate.Replace("[EXPIRYDATE]", ExpiryDate.ToShortDateString)
            Else
                strTemplate = strTemplate.Replace("[EXPIRYDATE]", "-")
            End If

            txtNotifyRoleBody.Content = strTemplate

        End Sub

        Private Sub BindUserCreateForm()

            pnlGrid.Visible = False
            pnlUser.Visible = False
            pnlCreate.Visible = True


            If ctlRoles.SelectedNode.Value <> PortalSettings.RegisteredRoleId.ToString Then
                If IsNumeric(ctlRoles.SelectedNode.Value) Then
                    Dim roleid As Integer = Convert.ToInt32(ctlRoles.SelectedNode.Value)
                    Try
                        Dim rc As New Security.Roles.RoleController
                        Dim role As RoleInfo = rc.GetRole(roleid, PortalId)
                        If Not role Is Nothing Then
                            lblCreateUserIntro.Text = String.Format(GetString("CreateAccountInRole", LocalResourceFile), rc.GetRole(roleid, PortalId).RoleName)
                        End If
                    Catch
                    End Try
                End If
            End If

            ProcessFormTemplate(plhCreate, Template_CreateAccount(CurrentLocale), Nothing, _PageNeedsToPostback)

        End Sub

        Private Sub UpdateAccount()

            Dim strMessage As String = ""

            Dim blnUpdateUsername As Boolean = False
            Dim blnUpdateDisplayname As Boolean = False
            Dim blnUpdateEmail As Boolean = False

            Dim txtUsername As RadTextBox = CType(FindControlRecursive(plhUser, plhUser.ID & "_" & Constants.ControlId_Username), RadTextBox)
            blnUpdateUsername = (Not txtUsername Is Nothing)

            If blnUpdateUsername AndAlso IsRegisterMode() Then
                If Not IsValidUserAttribute(Constants.User_Username, plhUser) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Username, plhUser)
                Else
                    RemoveErrorIndicator(Constants.User_Username, plhUser, True)
                End If
            End If

            Dim txtEmail As RadTextBox = CType(FindControlRecursive(plhUser, plhUser.ID & "_" & Constants.ControlId_Email), RadTextBox)
            blnUpdateEmail = (Not txtEmail Is Nothing)

            If blnUpdateEmail Then
                If Not IsValidUserAttribute(Constants.User_Email, plhUser) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Email, plhUser)
                Else
                    RemoveErrorIndicator(Constants.User_Email, plhUser, True)
                End If
            End If

            Dim txtDisplayName As RadTextBox = CType(FindControlRecursive(plhUser, plhUser.ID & "_" & Constants.ControlId_Displayname), RadTextBox)
            blnUpdateDisplayname = (Not txtDisplayName Is Nothing)

            If blnUpdateDisplayname Then
                If Not IsValidUserAttribute(Constants.User_Displayname, plhUser) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Displayname, plhUser)
                Else
                    RemoveErrorIndicator(Constants.User_Displayname, plhUser, True)
                End If
            End If

            If strMessage.Length > 0 Then
                Me.pnlAccountError.Visible = True
                Me.lblAccountError.Text = "<ul><li>" & GetString("FieldsRequired", LocalResourceFile) & "</li></ul>"
                Me.pnlAccountSuccess.Visible = False
                Me.pnlAccountIntro.Visible = False
                Exit Sub
            End If

            Dim oUser As UserInfo = User
            If blnUpdateDisplayname Then
                oUser.DisplayName = txtDisplayName.Text
            End If

            If blnUpdateEmail Then
                oUser.Email = txtEmail.Text
            End If

            If blnUpdateUsername Then
                oUser.Username = txtUsername.Text
            End If

            UserController.UpdateUser(PortalId, oUser)

            pnlAccountError.Visible = False
            pnlAccountSuccess.Visible = True
            pnlAccountIntro.Visible = False
            lblAccountSuccess.Text = "<ul><li>" & GetString("AccountDataUpdated", LocalResourceFile) & "</li></ul>"

        End Sub

        Private Sub UpdateProfile()

            Dim oUser As UserInfo = User
            Dim strMessage As String = ""

            For Each itemProp As String In GetPropertiesFromTempate(Template_EditProfile(CurrentLocale))
                Try
                    Dim prop As ProfilePropertyDefinition = ProfileController.GetPropertyDefinitionByName(PortalId, itemProp.Substring(2)) 'itemprop comes in the form U:Propertyname or P:Propertyname
                    If Not prop Is Nothing Then
                        If Not IsValidProperty(oUser, prop, plhProfile) Then
                            strMessage += "Error"
                            AddErrorIndicator(prop.PropertyDefinitionId.ToString, plhProfile)
                        Else
                            RemoveErrorIndicator(prop.PropertyDefinitionId.ToString, plhProfile, prop.Required)
                        End If
                    End If
                Catch
                End Try
            Next

            If strMessage.Length > 0 Then
                Me.pnlProfileError.Visible = True
                Me.lblProfileError.Text = "<ul><li>" & GetString("FieldsRequired", LocalResourceFile) & "</li></ul>"
                Me.pnlProfileSuccess.Visible = False
                Me.pnlProfileIntro.Visible = False
                Exit Sub
            End If

            'loop trough dynamic profile attributes and set those
            For Each itemProp As String In GetPropertiesFromTempate(Template_EditProfile(CurrentLocale))
                Try
                    Dim prop As ProfilePropertyDefinition = ProfileController.GetPropertyDefinitionByName(PortalId, itemProp.Substring(2))
                    If Not prop Is Nothing Then
                        Dim ctl As Control = GetPropertyControl(prop, plhProfile)
                        If Not ctl Is Nothing Then
                            If TypeOf (ctl) Is Telerik.Web.UI.RadComboBox Then
                                oUser.Profile.SetProfileProperty(prop.PropertyName, CType(ctl, Telerik.Web.UI.RadComboBox).SelectedValue.Trim)
                            ElseIf TypeOf (ctl) Is Telerik.Web.UI.RadDateTimePicker Then
                                oUser.Profile.SetProfileProperty(prop.PropertyName, CType(ctl, Telerik.Web.UI.RadDateTimePicker).DbSelectedDate.ToString)
                            ElseIf TypeOf (ctl) Is Telerik.Web.UI.RadTimePicker Then
                                oUser.Profile.SetProfileProperty(prop.PropertyName, CType(ctl, Telerik.Web.UI.RadTimePicker).DbSelectedDate.ToString)
                            ElseIf TypeOf (ctl) Is CheckBox Then
                                oUser.Profile.SetProfileProperty(prop.PropertyName, CType(ctl, CheckBox).Checked.ToString)
                            ElseIf TypeOf (ctl) Is Telerik.Web.UI.RadTextBox Then
                                oUser.Profile.SetProfileProperty(prop.PropertyName, CType(ctl, Telerik.Web.UI.RadTextBox).Text.Trim)


                                If prop.PropertyName.ToLower = "firstname" Then
                                    oUser.FirstName = CType(ctl, Telerik.Web.UI.RadTextBox).Text.Trim
                                End If

                                If prop.PropertyName.ToLower = "lastname" Then
                                    oUser.LastName = CType(ctl, Telerik.Web.UI.RadTextBox).Text.Trim
                                End If

                            ElseIf TypeOf (ctl) Is Telerik.Web.UI.RadNumericTextBox Then
                                oUser.Profile.SetProfileProperty(prop.PropertyName, CType(ctl, Telerik.Web.UI.RadNumericTextBox).Value.ToString)
                            ElseIf TypeOf (ctl) Is Telerik.Web.UI.RadAsyncUpload Then

                                Dim objFile As UploadedFile = CType(ctl, Telerik.Web.UI.RadUpload).UploadedFiles(0)
                                If Not objFile Is Nothing Then
                                    Dim strFile As String = objFile.GetName
                                    Dim path As String = "Profile/" & prop.PropertyName & "/" & oUser.Username & "/" & strFile

                                    oUser.Profile.SetProfileProperty(prop.PropertyName, path)

                                End If

                            End If

                        End If

                    End If
                Catch
                End Try
            Next


            UserController.UpdateUser(PortalId, oUser)

            pnlProfileError.Visible = False
            pnlProfileSuccess.Visible = True
            pnlProfileIntro.Visible = False
            lblProfileSuccess.Text = "<ul><li>" & GetString("ProfileUpdated", LocalResourceFile) & "</li></ul>"

            ProcessFormTemplate(plhProfile, Template_EditProfile(CurrentLocale), User, _PageNeedsToPostback)

        End Sub

        Private Function GetUserList() As DataSet

            Dim intRole As Integer = Null.NullInteger
            Dim strSearch As String = Null.NullString
            Dim blnShowDeleted As Boolean = False
            Dim blnUseCache As Boolean = True

            If txtSearch.Text.Length > 0 Then

                strSearch = txtSearch.Text.Trim
                intRole = PortalSettings.RegisteredRoleId
                blnUseCache = False

                If ctlRoles.SelectedNode.Value <> PortalSettings.RegisteredRoleId.ToString And Not ctlRoles.SelectedNode.Value = "-2" Then
                    ctlRoles.UnselectAllNodes()
                    Try
                        ctlRoles.FindNodeByValue(PortalSettings.RegisteredRoleId.ToString).Selected = True
                    Catch
                    End Try
                End If

            Else

                If Not ctlRoles.SelectedNode Is Nothing Then
                    If CType(ctlRoles.SelectedNode.Attributes("IsGroup"), Boolean) = False Then
                        Try
                            intRole = Convert.ToInt32(ctlRoles.SelectedNode.Value)
                        Catch
                        End Try
                    End If
                End If

            End If

            If Not ctlRoles.SelectedNode Is Nothing Then
                If ctlRoles.SelectedNode.Value = "-2" Then
                    blnShowDeleted = True
                    blnUseCache = False
                End If
            End If            

            Dim ds As DataSet = Nothing

            If intRole <> Null.NullInteger Then

                If blnUseCache Then
                    ds = GetCachedUserList(intRole)
                End If

                If ds Is Nothing Then

                    Dim strCols As String = ""
                    For Each item As ListItem In chkSearchCols.Items
                        If item.Selected = True Then
                            strCols += item.Value & ","
                        End If
                    Next

                    ds = DotNetNuke.Data.DataProvider.Instance().ExecuteDataSet("dnnWerk_GetUserList", intRole, PortalId, DotNetNuke.Data.DataProvider.Instance().GetNull(strSearch), strCols, blnShowDeleted)

                    If blnShowDeleted = False AndAlso strSearch = Null.NullString Then
                        CacheUserList(intRole, ds)
                    End If

                End If

                If blnShowDeleted = True Then
                    If ds.Tables(0).Rows.Count > 0 Then
                        btnHardDelete.Visible = AllowHardDelete
                    Else
                        btnHardDelete.Visible = False
                    End If
                Else
                    btnHardDelete.Visible = False
                End If

            End If

            Return ds

        End Function

        Private Function GetCachedUserList(ByVal RoleId As Integer) As DataSet
            Dim ds As DataSet = Nothing
            If Not DataCache.GetCache("DNNWERK_USERLIST_ROLEID" & RoleId.ToString) Is Nothing Then
                Return CType(DataCache.GetCache("DNNWERK_USERLIST_ROLEID" & RoleId.ToString), DataSet)
            End If
            Return ds
        End Function

        Private Sub CacheUserList(ByVal RoleId As Integer, ByVal ds As DataSet)
            If Not DataCache.GetCache("DNNWERK_USERLIST_ROLEID" & RoleId.ToString) Is Nothing Then
                DataCache.RemoveCache("DNNWERK_USERLIST_ROLEID" & RoleId.ToString)
            End If
            DataCache.SetCache("DNNWERK_USERLIST_ROLEID" & RoleId.ToString, ds)
        End Sub

        Private Sub ClearCache()

            Dim objRoleController As New RoleController
            Dim roles As ArrayList = objRoleController.GetPortalRoles(PortalId)
            For Each role As RoleInfo In roles
                If Not DataCache.GetCache("DNNWERK_USERLIST_ROLEID" & role.RoleID.ToString) Is Nothing Then
                    DataCache.RemoveCache("DNNWERK_USERLIST_ROLEID" & role.RoleID.ToString)
                End If
            Next

        End Sub

        Private Sub HardDeleteAccount(ByVal intUser As Integer, ByVal strUser As String)

            DotNetNuke.Data.DataProvider.Instance().ExecuteNonQuery("dnnWerk_Users_HardDeleteUser", intUser)
            System.Web.Security.Membership.DeleteUser(strUser, True)

        End Sub

        Private Sub RestoreAccount(ByVal intUser As Integer)

            DotNetNuke.Data.DataProvider.Instance().ExecuteNonQuery("dnnWerk_Users_RestoreUser", intUser)

            Dim oUser As UserInfo = UserController.GetUserById(PortalId, intUser)
            Dim rC As New RoleController
            If Not oUser Is Nothing Then

                rC.AddUserRole(PortalId, oUser.UserID, PortalSettings.RegisteredRoleId, Date.Now, Null.NullDate)

                For Each objRole As RoleInfo In rC.GetPortalRoles(PortalId)
                    If objRole.AutoAssignment = True Then
                        rC.AddUserRole(PortalId, oUser.UserID, objRole.RoleID, Date.Now, Null.NullDate)
                    End If
                Next

                oUser.Membership.Approved = True
                UserController.UpdateUser(PortalId, oUser, True)

            End If

        End Sub

        Private Sub BindReports()

            drpReports.Items.Clear()
            drpReports.Items.Add(New RadComboBoxItem(GetString("SelectReport", LocalResourceFile), "-1"))

            Dim dr As IDataReader = DotNetNuke.Data.DataProvider.Instance().ExecuteReader("dnnWerk_Users_GetReports", PortalId)
            While dr.Read
                Dim strText As String = Convert.ToString(dr("FriendlyName"))
                Dim strValue As String = Convert.ToString(dr("ReportId"))
                drpReports.Items.Add(New RadComboBoxItem(strText, strValue))
            End While
            dr.Close()
            dr.Dispose()

        End Sub

        Private Function GetSQL(ByVal ReportId As Integer) As String

            Dim strSql As String = ""

            Dim dr As IDataReader = DotNetNuke.Data.DataProvider.Instance().ExecuteReader("dnnWerk_Users_GetReport", ReportId)
            While dr.Read
                strSql = Convert.ToString(dr("SQL"))
            End While
            dr.Close()
            dr.Dispose()

            Return strSql

        End Function

        Private Function GetReportResult(ByRef strError As String) As DataSet

            Dim ds As New DataSet()
            Dim userTable As New DataTable("UsersTable")
            ds.Tables.Add(userTable)
            Try
                Dim sql As String = GetSQL(Convert.ToInt32(drpReports.SelectedValue))
                If Not sql Is Nothing Then
                    If sql.Length > 0 Then
                        Try
                            Dim dr As IDataReader = DotNetNuke.Data.DataProvider.Instance().ExecuteSQL(sql)
                            ds.Load(dr, LoadOption.OverwriteChanges, userTable)
                        Catch ex As Exception
                            'error in sql syntax (most likely)
                            strError = "Your query contains errors, please check the report settings!"
                        End Try
                    End If
                End If
            Catch ex As Exception

            End Try


            Return ds

        End Function

        Private Sub Export()

            Dim users As New List(Of UserInfo)
            Dim ds As DataSet = Nothing
            Dim strError As String = ""

            If ctlRoles.SelectedNode Is Nothing Then
                _IsReportResult = True
            End If

            If _IsReportResult Then
                ds = GetReportResult(strError)
            Else
                ds = GetUserList()               
            End If

            If Not ds Is Nothing Then
                For Each row As DataRow In ds.Tables(0).Rows
                    Dim oUser As UserInfo = UserController.GetUserById(PortalId, row("UserId"))
                    If Not oUser Is Nothing Then
                        users.Add(oUser)
                    End If
                Next
            End If
           

            Dim sFilename As String = "Members"

            Try
                sFilename = "Members_" & ctlRoles.SelectedNode.Text
            Catch
            End Try

            Response.ClearHeaders()
            Response.ClearContent()
            Response.ContentType = "application/vnd.ms-excel"
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("ISO-8859-1")
            Response.AppendHeader("content-disposition", "attachment;filename=" & sFilename & ".xls")


            For Each strHeader As String In ExportFieldHeaders
                Response.Write(strHeader & Microsoft.VisualBasic.ControlChars.Tab)
            Next
            Response.Write(vbCrLf)

            For Each oUser As UserInfo In users
                For Each strField As String In ExportFields
                    Select Case strField.ToLower
                        Case "user_userid"
                            Response.Write(oUser.UserID.ToString & Microsoft.VisualBasic.ControlChars.Tab)
                        Case "user_username"
                            Response.Write(oUser.Username & Microsoft.VisualBasic.ControlChars.Tab)
                        Case "user_firstname"
                            Response.Write(oUser.FirstName & Microsoft.VisualBasic.ControlChars.Tab)
                        Case "user_lastname"
                            Response.Write(oUser.LastName & Microsoft.VisualBasic.ControlChars.Tab)
                        Case "user_email"
                            Response.Write(oUser.Email & Microsoft.VisualBasic.ControlChars.Tab)
                        Case "user_createddate"
                            Response.Write(oUser.Membership.CreatedDate.ToShortDateString & Microsoft.VisualBasic.ControlChars.Tab)
                        Case "user_lastlogindate"
                            Response.Write(oUser.Membership.LastLoginDate.ToShortDateString & Microsoft.VisualBasic.ControlChars.Tab)
                        Case "user_displayname"
                            Response.Write(oUser.DisplayName & Microsoft.VisualBasic.ControlChars.Tab)
                        Case Else
                            If Not String.IsNullOrEmpty(oUser.Profile.GetPropertyValue(strField)) Then
                                Response.Write(oUser.Profile.GetPropertyValue(strField) & Microsoft.VisualBasic.ControlChars.Tab)
                            Else
                                Response.Write("" & Microsoft.VisualBasic.ControlChars.Tab)
                            End If
                    End Select
                Next
                Response.Write(vbCrLf)
            Next

            Response.End()

        End Sub

        Public Function InvalidEmailString() As String
            Return Localization.GetString("InvalidPassword.Text", SharedResourcefile)
        End Function

        Public Function ValidPasswordString() As String
            Return Localization.GetString("ValidPassword.Text", SharedResourcefile)
        End Function

        Public Function InvalidPasswordString() As String
            Return Localization.GetString("InvalidPassword.Text", SharedResourcefile)
        End Function

        Public Function PasswordsDontMatchString() As String
            Return Localization.GetString("PasswordsDontMatch.Text", SharedResourcefile)
        End Function

        Public Function MinPasswordLength() As String
            Return "7"
        End Function

        Public Function ErrorImageUrl() As String
            Return (Me.ModuleDirectory & "/images/error.png").Replace("~", "")
        End Function

        Public Function AcceptImageUrl() As String
            Return (Me.ModuleDirectory & "/images/accept.png").Replace("~", "")
        End Function

        Public Function Password1Id() As String
            Return txtPassword1.ClientID
        End Function

        Public Function Password2Id() As String
            Return txtPassword2.ClientID
        End Function

#End Region

    End Class

End Namespace
